What I’m trying to do is to ask a user for a name of a file to make and then save some stuff in this file.
My portion of the program looks like this:
if saving == 1:
ask=raw_input("Type the name file: ")
fileout=open(ask.csv,"w")
fileout.write(output)
I want the format to be .csv, I tried different options but can’t seem to work.
The issue here is you need to pass
open()a string.askis a variable that contains a string, but we also want to append the other string".csv"to it to make it a filename. In python+is the concatenation operator for strings, soask+".csv"means the contents of ask, followed by .csv. What you currently have is looking for thecsvattribute of theaskvariable, which will throw an error.You might also want to do a check first if the user has already typed the extension:
Note my use of the
withstatement when opening files. It’s good practice as it’s more readable and ensures the file is closed properly, even on exceptions.I am also using the python ternary operator here to do a simple variable assignment based on a condition (setting ask to itself if it already ends in
".csv", otherwise concatenating it).Also, this is presuming your output is already suitable for a CSV file, the extension alone won’t make it CSV. When dealing with CSV data in general, you probably want to check out the csv module.