2016-10-11 173 views
4

我想创建一个临时文件,我从另一个文件的某些行写入,然后从数据中创建一些对象。我不知道如何找到并打开临时文件,以便我可以阅读它。我的代码:Python - 写入和读取临时文件

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() 

本质上,我只是想做一个中间人临时文件,以防止意外覆盖文件。

+0

我从来没有使用的临时文件,是否有你arn't使用标准'的open()''write'和'read'方法的原因吗? – kpie

+0

我想防止文件名已存在的可能性,我可以覆盖它 –

+0

1.您是否考虑过简单地将输出从一个脚本输送到第二个脚本的输入? 2.您是否正在检查以确保临时文件存在于您正在查找的路径中? – erapert

回答

6

根据docs,当TemporaryFile已关闭,并且退出with子句时发生该错误。所以......不要退出with条款。倒带文件并在with中完成您的工作。

with tempfile.TemporaryFile() as tmp: 
    lines = open(file1).readlines() 
    tmp.writelines(lines[2:-1]) 
    tmp.seek(0) 

    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) 
+0

谢谢你解决了它。 .seek(0)完成了什么? –

+0

是你正在谈论的倒带? –

+2

在'tmp.writelines'之后,文件指针位于文件末尾。 'tmp.seek(0)'把它重新放回到头部(倒带它 - 也许这是古老的盒式磁带隐语!),所以你可以阅读你写的东西。 – tdelaney

5

你有一个范围问题;文件tmp只存在于创建它的with语句的范围内。此外,如果您想在初始with之外访问该文件(这使操作系统能够访问该文件),则需要使用NamedTemporaryFile。另外,我不确定你为什么试图附加到一个临时文件...因为它在实例化之前不会存在。

试试这个:

import tempfile 

tmp = tempfile.NamedTemporaryFile() 

# Open the file for writing. 
with open(tmp.name, 'w') as f: 
    f.write(stuff) # where `stuff` is, y'know... stuff to write (a string) 

... 

# Open the file for reading. 
with open(tmp.name) as f: 
    for line in f: 
     ... # more things here 
+0

还要确保在写入文件后添加“f.seek(0)”,如果要从中读取而不关闭并重新打开文件。否则,你会读取文件的结尾,这会给你错误的结果。 – jelde015