Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inserting variable string as file name

Tags:

I'm trying to create a file with a unique file name for every time my script runs. I am only intending to do this to every week or month. so I chose to use the date for the file name.

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

is where I'm getting 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 filename, is there an issue with the open function, that means you can't pass a string like this?

name is a string and has values such as :

31/1/2013BVI 

Many thanks for any help.

like image 776
jbaldwin Avatar asked Jan 31 '13 09:01

jbaldwin


2 Answers

You need to put % name straight after the string:

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

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

like image 61
Volatility Avatar answered Sep 24 '22 16:09

Volatility


you can do something like

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

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

like image 26
avasal Avatar answered Sep 23 '22 16:09

avasal