簡體   English   中英

如何將臨時文件(圖像、txt 等)添加到臨時目錄,然后在 Python 中訪問它們?

[英]How to add temp files (images, txt, etc) to a temp directory and then access them in Python?

我想創建一個名為 workdir 的臨時目錄,在其中我想寫一些文件並添加一些圖像,然后讀取這些文件和圖像。 但我不明白我怎么能做到這一點。 我是 python 的新手,只知道基礎知識,所以如果有人可以幫助我,我將不勝感激。

這是我從 stackoverflow 中選擇的一個示例,因為它是選擇的答案,但它對我不起作用。

import tempfile
import os

with tempfile.TemporaryDirectory() as workdir:

    print('tmp dir name', workdir)

    # write file to tmp dir
    fout = open(os.path.join(workdir,'file.txt'), 'w')
    fout.write('test write')
    fout.close()

    print('file.txt location', workdir + 'lala.fasta')

    # working with the file is fine
    fin = open(workdir + 'file.txt', 'U')
    for line in fin:
        print(line)

    
    for file in os.listdir(workdir):
        print('searching in directory')
        print(file)

這是不正確的:

# working with the file is fine
fin = open(workdir + 'file.txt', 'U')

workdir沒有尾隨/ ,因此它嘗試打開的文件的路徑是/tmp/tmp4r1zdpqmfile.txt (如錯誤中所述),而不是預期的/tmp/tmp4r1zdpqm/file.txt 使用os.path.join() (正如之前寫入文件時所做的那樣)以允許目錄和文件的平台不可知組合。

此外,不推薦使用'U'文件選項。 請改用'w''r''r+'之類的東西。 有關詳細信息,請參閱官方文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM