python插入变量字符串作为文件名 [英] python inserting variable string as file name
问题描述
我试图创建一个具有唯一文件名的文件,每次运行脚本时,它只打算每周或每月一次.所以我选择使用日期作为文件名.
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是一个字符串,并具有以下值:
name is a string and has values such as :
31/1/2013BVI
非常感谢您的帮助
推荐答案
您需要在字符串后直接放置% name
:
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.
这篇关于python插入变量字符串作为文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!