python插入变量字符串作为文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14622314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python inserting variable string as file name
提问by jbaldwin
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?
如果我使用静态文件名,它会起作用,open 函数是否存在问题,这意味着您不能传递这样的字符串?
name is a string and has values such as :
name 是一个字符串,具有如下值:
31/1/2013BVI
Many thanks for any help
非常感谢您的帮助
采纳答案by Volatility
You need to put % namestraight after the string:
您需要% name在字符串之后直接放置:
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.
您的代码不起作用的原因是因为您正在尝试%一个不是字符串格式的文件,并且也是无效的。
回答by avasal
you can do something like
你可以做类似的事情
filename = "%s.csv" % name
f = open(filename , 'wb')
or f = open('%s.csv' % name, 'wb')
或者 f = open('%s.csv' % name, 'wb')
回答by peixe
And with the new string formatting method...
并使用新的字符串格式化方法...
f = open('{0}.csv'.format(name), 'wb')
回答by ran632
Very similar to peixe.
You don't have to mention the number if the variables you add as parameters are in order of appearance
非常类似于peixe。
如果作为参数添加的变量是按出现顺序排列的,则不必提及数字
f = open('{}.csv'.format(name), 'wb')
回答by Tom Lubenow
Even better are f-strings in python 3!
更好的是python 3中的f字符串!
f = open(f'{name}.csv', 'wb')
回答by Ndondz
f = open('{}.csv'.format(), 'wb')
f = open('{}.csv'.format(), 'wb')

