我试图创建一个临时文件,我从另一个文件中写入一些行,然后从数据中创建一些对象。我不知道如何找到和打开临时文件,以便我可以阅读它。我的代码:
with tempfile.TemporaryFile() as tmp:
lines = open(file1).readlines()
tmp.writelines(lines[2:-1])
dependencyList = []
for line in tmp:
groupId = textwrap.dedent(line.split(':')[0])
artifactId = line.split(':')[1]
version = line.split(':')[3]
scope = str.strip(line.split(':')[4])
dependencyObject = depenObj(groupId, artifactId, version, scope)
dependencyList.append(dependencyObject)
tmp.close()
本质上,我只是想做一个中间人临时文件,以防止意外覆盖文件。
根据docs,文件在
TemporaryFile
关闭时被删除,在退出with
子句时也会被删除。所以。。。不要退出with
子句。倒带文件并在with
中执行工作。您遇到了范围问题;文件
tmp
只存在于创建它的with
语句的范围内。此外,如果您想稍后在初始with
之外访问该文件,则需要使用NamedTemporaryFile
(这使操作系统能够访问该文件)。另外,我不知道你为什么要附加到一个临时文件。。。因为在你实例化它之前它是不存在的。试试这个:
如果需要再次打开该文件,例如由另一个进程读取此might cause trouble on Windows OS:
因此,一个安全的解决方案是create a temporary directory,然后在其中手动创建一个文件:
相关问题 更多 >
编程相关推荐