Skip to main content
 首页 » 编程设计

python之如何在 Python 中写入临时文件并再次从中读取

2025年05月04日13txw1958

我正在尝试为将数据写入 CSV 文件的函数编写单元测试。为此,我想使用 tempfile.NamedTemporaryFile写入一个命名的临时文件并再次打开它,我从文档中了解到这在 Unix 平台上应该是可能的。

但是,如果我尝试这个测试,

import csv 
import tempfile 
 
 
def write_csv(csvfile): 
    writer = csv.DictWriter(csvfile, fieldnames=['foo', 'bar']) 
 
    writer.writeheader() 
    writer.writerow({'foo': 1, 'bar': 2}) 
 
 
def test_write_csv(): 
    with tempfile.NamedTemporaryFile(mode='w') as csvfile: 
        write_csv(csvfile) 
 
    with open(csvfile.name) as csvfile: 
        reader = csv.DictReader(csvfile) 

我得到一个FileNotFoundError:

> pytest csvtest.py -s 
======================================= test session starts ======================================== 
platform darwin -- Python 3.7.3, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 
rootdir: /Users/kurtpeek/Documents/Scratch 
collected 1 item                                                                                    
 
csvtest.py F 
 
============================================= FAILURES ============================================= 
__________________________________________ test_write_csv __________________________________________ 
 
    def test_write_csv(): 
        with tempfile.NamedTemporaryFile(mode='w') as csvfile: 
            write_csv(csvfile) 
 
>       with open(csvfile.name) as csvfile: 
E       FileNotFoundError: [Errno 2] No such file or directory: '/var/folders/fr/7gjx_3js67xg0pjxz6sptktc0000gn/T/tmpgml8_fwf' 
 
csvtest.py:16: FileNotFoundError 
===================================== 1 failed in 0.03 seconds ===================================== 

我已经尝试了各种替代方法,比如尝试在编写文件时在同一个 with block 中打开文件(在这种情况下我得到一个错误,它没有打开供阅读),打开'rw' 模式(在这种情况下 csv 不允许我写入)。

如何将 CSV 写入临时文件并在单元测试中再次读取?

请您参考如下方法:

如果想在关闭后保留临时文件,需要传入delete=False。来自 tempfile.NamedTemporaryFile 的文档您链接的:

If delete is true (the default), the file is deleted as soon as it is closed.

然后你只需要做:

import csv 
import tempfile 
 
def write_csv(csvfile): 
    writer = csv.DictWriter(csvfile, fieldnames=['foo', 'bar']) 
    writer.writeheader() 
    writer.writerow({'foo': 1, 'bar': 2}) 
 
def test_write_csv(): 
    with tempfile.NamedTemporaryFile(mode='w', delete=False) as csvfile: 
        write_csv(csvfile) 
    with open(csvfile.name) as csvfile: 
        reader = csv.DictReader(csvfile)