Python inserting variable string as file name

I try to create a file file with a unique file name, every time my script is executed, it is intended only for weekly or monthly. so I decided to use a date for the file name.

f = open('%s.csv', 'wb') %name 

where i get this error.

 Traceback (most recent call last): File "C:\Users\User\workspace\new3\stjohnsinvoices\BabblevoiceInvoiceswpath.py", line 143, in <module> f = open('%s.csv', 'ab') %name TypeError: unsupported operand type(s) for %: 'file' and 'str' 

It works, if I use a static file name, is there a problem with an open function, so you can not pass such a line?

name is a string and has values ​​such as:

 31/1/2013BVI 

Thanks so much for any help

+12
python file
source share
5 answers

You need to put % name right after the line:

 f = open('%s.csv' % name, 'wb') 

The reason your code doesn’t work is because you are trying to execute a % file, which is not formatting a string and is also invalid.

+31
source share

you can do something like

 filename = "%s.csv" % name f = open(filename , 'wb') 

or f = open('%s.csv' % name, 'wb')

+5
source share

And using the newline formatting method ...

 f = open('{0}.csv'.format(name), 'wb') 
+3
source share

Very similar to peixe.
You do not need to mention the number if the variables added as parameters look in the order of appearance

 f = open('{}.csv'.format(name), 'wb') 
+2
source share

Even better f-strings in Python 3!

 f = open(f'{name}.csv', 'wb') 
0
source share

All Articles