简体   繁体   English

如何从临时文件对象获取文件名?

[英]How do I get the filename from a tempfile object?

My goal is to create a temporary file that's written by csv.writer which will be used in an upload to a database.我的目标是创建一个由 csv.writer 编写的临时文件,该文件将用于上传到数据库。 Once the upload completes, I want to delete the file.上传完成后,我想删除该文件。

The upload and deletion portions are not included here as I haven't fully built it out but I need to get past this part first.这里不包括上传和删除部分,因为我还没有完全构建它,但我需要先通过这部分。

import csv, io, tempfile

filename = tempfile.NamedTemporaryFile(suffix='.csv', delete=False)

file = io.StringIO(report_downloader.DownloadReportAsString(report, skip_report_header=False, skip_column_header=False, skip_report_summary=True))
reader = csv.reader(file)

with open(filename, 'w', encoding='utf8', newline='') as f:
    writer = csv.writer(f, delimiter=',')
    for row in reader:
        writer.writerows([row])     

The resulting error from doing this is:这样做导致的错误是:

Traceback (most recent call last):
File "aw-ad-performance-tempfile.py", line 99, in <module> get_api_report()
File "aw-ad-performance-tempfile.py", line 92, in get_api_report
with open(filename, 'w', encoding='utf8', newline='') as f:

OSError: [Errno 22] Invalid argument:'<tempfile._TemporaryFileWrapper object at 0x00000274FBED0FD0>'

I've tried a few different ways of addressing the problem and I've identified that it expects a string where filename is here:我尝试了几种不同的方法来解决这个问题,我发现它需要一个字符串,其中文件名在这里:

with open(filename, 'w', encoding='utf8', newline='') as f:

Is it possible to reference the temporary file as a string using the tempfile module so csv.writer recognizes it?是否可以使用 tempfile 模块将临时文件作为字符串引用,以便 csv.writer 识别它? What's the syntax to do so if it is?如果是的话,这样做的语法是什么?

You're on the right track.你在正确的轨道上。 You need reference your file with the .name attribute of your tempfile.NamedTemporaryFile object.您需要使用tempfile.NamedTemporaryFile对象的.name属性来引用您的文件。 See the documentation here.请参阅此处的文档

with open(filename.name, 'w', encoding='utf8', newline='') as f:
    writer = csv.writer(f, delimiter=',')
        for row in reader:
            writer.writerows([row])   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM