gpt4 book ai didi

python - 在 Python3 的 tempfile.TemporaryDirectory() 中找不到文件

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:36 26 4
gpt4 key购买 nike

我一般在使用 Python3 的临时文件库时遇到问题。

我需要在一个临时目录中写入一个文件,并确保它在那里。我使用的第三方软件工具有时会失败,所以我不能直接打开文件,我需要先使用“while 循环”或其他方法验证它是否存在,然后再打开它。所以我需要搜索 tmp_dir(使用 os.listdir() 或等价物)。

具体帮助/解决方案和一般帮助将在评论中表示赞赏。

谢谢。

小示例代码:

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斜杠反斜杠)。所以文件是在错误的级别创建的。

tmp_dir = D:\Users\foo\AppData\Local\Temp\tmpm_x5z4tx
tmp_dir + "file.txt"
=> D:\Users\foo\AppData\Local\Temp\tmpm_x5z4txfile.txt

相反,join在临时目录中获取文件的两条路径:

fout = open(os.path.join(tmp_dir,'file.txt'), 'w')

请注意 fin = open(tmp_dir + 'file.txt', 'U')找到文件,这是预期的,但它在 tmp_dir 所在的同一目录中找到它已创建。

关于python - 在 Python3 的 tempfile.TemporaryDirectory() 中找不到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44974899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com