My goal is to create a temporary file that's written by csv.writer which will be used in an upload to a database. 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? What's the syntax to do so if it is?
To view and delete temp files, open the Start menu and type %temp% in the Search field. In Windows XP and prior, click the Run option in the Start menu and type %temp% in the Run field. Press Enter and a Temp folder should open.
Alternatively referred to as a foo file, a temporary file or temp file is a file created to hold information while a file's being created or modified.
Source code: Lib/tempfile.py. This module creates temporary files and directories. It works on all supported platforms. TemporaryFile , NamedTemporaryFile , TemporaryDirectory , and SpooledTemporaryFile are high-level interfaces which provide automatic cleanup and can be used as context managers.
You're on the right track. You need reference your file with the .name
attribute of your tempfile.NamedTemporaryFile
object. 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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With