python inserting variable string as file name

2020-01-30 08:02发布

I'm trying to create a file file a unique file name, every time my script is ran, it's only intended to be weekly or monthly. 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

5条回答
冷血范
2楼-- · 2020-01-30 08:21

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.

查看更多
Animai°情兽
3楼-- · 2020-01-30 08:24

Even better are f-strings in python 3!

f = open(f'{name}.csv', 'wb')
查看更多
孤傲高冷的网名
4楼-- · 2020-01-30 08:26

And with the new string formatting method...

f = open('{0}.csv'.format(name), 'wb')
查看更多
家丑人穷心不美
5楼-- · 2020-01-30 08:34

Very similar to peixe.
You don't have to mention the number if the variables you add as parameters are in order of appearance

f = open('{}.csv'.format(name), 'wb')
查看更多
戒情不戒烟
6楼-- · 2020-01-30 08:41

you can do something like

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

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

查看更多
登录 后发表回答