我在使用Python3的tempfile库时遇到了困难。在
我需要在临时目录中写一个文件,并确保它在那里。我使用的第三方软件工具有时会失败,所以我不能直接打开文件,我需要先用“while循环”或其他方法验证它是否在那里,然后再打开它。所以我需要搜索tmp_dir(使用操作系统列表目录()或等效物)。在
如能提供具体帮助/解决方案和一般帮助,我们将不胜感激。在
谢谢。在
小样本代码:
import os
import tempfile
with tempfile.TemporaryDirectory() as tmp_dir:
print('tmp dir name', tmp_dir)
# write file to tmp dir
fout = open(tmp_dir + 'file.txt', 'w')
fout.write('test write')
fout.close()
print('file.txt location', tmp_dir + 'lala.fasta')
# working with the file is fine
fin = open(tmp_dir + 'file.txt', 'U')
for line in fin:
print(line)
# but I cannot find the file in the tmp dir like I normally use os.listdir()
for file in os.listdir(tmp_dir):
print('searching in directory')
print(file)
这是预期的,因为临时目录名不以路径分隔符结尾(
os.sep
,斜杠或反斜杠在许多系统上)。所以文件是在错误的级别创建的。在取而代之,
^{pr2}$join
在临时目录中获取文件的两个路径:注意,
fin = open(tmp_dir + 'file.txt', 'U')
找到了预期的文件,但是它在创建tmp_dir
的同一目录中找到了它。在相关问题 更多 >
编程相关推荐