[英]how to create file names from a number plus a suffix in python
how to create file names from a number plus a suffix??. 如何从数字加后缀创建文件名?
for example I am using two programs in python script for work in a server, the first creates a file x and the second uses the x file, the problem is that this file can not overwrite. 例如,我正在python脚本中使用两个程序在服务器上工作,第一个创建文件x,第二个使用x文件,问题是此文件无法覆盖。
no matter what name is generated from the first program. 无论从第一个程序生成什么名称。 the second program of be taken exactly from the path and file name that was assigned to continue the script.
第二个程序完全取自为继续执行脚本而分配的路径和文件名。
thanks for your help and attention 感谢您的帮助和关注
As far as I can understand you, you want to create a file with a unique name in one program and pass the name of that file to another program. 据我了解,您想在一个程序中创建一个具有唯一名称的文件,然后将该文件的名称传递给另一个程序。 I think you should take a look at the tempfile module, http://docs.python.org/library/tempfile.html#module-tempfile .
我认为您应该看看tempfile模块http://docs.python.org/library/tempfile.html#module-tempfile 。
Here is an example that makes use of NamedTemporaryFile: 这是一个使用NamedTemporaryFile的示例:
import tempfile
import os
def produce(text):
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
f.write(text)
return f.name
def consume(filename):
try:
with open(filename) as f:
return f.read()
finally:
os.remove(filename)
if __name__ == '__main__':
filename = produce('Hello, world')
print('Filename is: {0}'.format(filename))
text = consume(filename)
print('Text is: {0}'.format(text))
assert not os.path.exists(filename)
The output is something like this: 输出是这样的:
Filename is: /tmp/tmpp_iSrw.txt
Text is: Hello, world
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.