Can't find file in my tempfile.TemporaryDirectory () for Python3
I'm having trouble working with the Python3 file library in general.
I need to write a file in a temporary directory and make sure it is there. The third party software tool I use sometimes fails, so I can't just open the file, I need to check it there first using a "while loop" or some other method before just opening it. So I need to search for tmp_dir (using os.listdir () or equivalent).
Concrete help / solution and general help would be appreciated in the comments.
Thank.
Small sample code:
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)
source to share
This was expected because the temporary directory name does not end with a path separator ( os.sep
such as a slash or backslash on many systems). So the file is being generated at the wrong level.
tmp_dir = D:\Users\T0024260\AppData\Local\Temp\tmpm_x5z4tx
tmp_dir + "file.txt"
=> D:\Users\T0024260\AppData\Local\Temp\tmpm_x5z4txfile.txt
Instead, join
both paths to get the file inside your temp directory:
fout = open(os.path.join(tmp_dir,'file.txt'), 'w')
note that it fin = open(tmp_dir + 'file.txt', 'U')
finds the expected file, but finds it in the same directory where it was created tmp_dir
.
source to share