Python- creating a text file with a variable as a name
13,469
Solution 1
Replace this line:
with open( 'Green Bottles.txt', 'w') as a:
With
with open(numbers[num1] + ' Green Bottles.txt', 'w') as a:
This will prepend your file name with the appropriate word.
Solution 2
You could give the name of the file to a function and return the file.
def write(nameOfFile):
print('Creating new text file')
name = nameOfFile+'.txt' # Name of text file coerced with +.txt
try:
file = open(name,'r+') # Trying to create a new file or open one
return file
except:
print('Something went wrong! Can\'t tell what?')
sys.exit(0) # quit Python
a = write(numbers[num1] )
Solution 3
You can add your input to file name using string format
use
with open('%s Green Bottles.txt' % numbers[num1], 'w') as a:
Comments
-
Phayer almost 2 years
So im doing a project where my program creates a textfile named "Ten Green Bottles" and writes the 10 green bottles song in it, I have successfully got it working but i want to make it better. I started by making the amount of bottles optional to the user and it worked fine. Now i just want the name to be relevent with the amount of bottles input by the user. ie, if I put in 20 bottles i want the name of the text file to be "Twenty Green Bottles" rather than "Ten Green Bottles" Code:
num1=int(input('Pick a number between 10 and 30: ')) def main(): numbers =[ 'no', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', 'Twenty', 'Twentyone', 'Twentytwo', 'Twentythree', 'Twentyfour', 'Twentyfive', 'Twentysix', 'Twentyseven', 'Twentyeight', 'Twentynine', 'Thirty' ] text_one = 'green bottle%s\nHanging on the wall' text_two = "\nAnd if one green bottle\nShould accidentally fall\nThere'll be" text_three =' \n' with open( 'Green Bottles.txt', 'w') as a: for l in range(num1, 0, -1): a.write(numbers[l]+ ' ') if l == 1: a.write(text_one % '' +'\n') else: a.write(text_one % 's' +'\n') a.write(numbers[l] + ' ') if l == 1: a.write(text_one % '' + '\n') else: a.write(text_one % 's' + '\n') a.write(text_two + ' ') a.write(numbers[l-1] + ' ') if (l - 1) ==1 : a.write(text_one % ''+'\n') else: a.write(text_one % 's'+'\n') a.write('\n' + '\n') if __name__ == '__main__': main()