我有一个场景,我必须打开一个临时文件,将 csv 数据写入其中,然后将其作为 POST 调用的附件读取,然后将其删除。
我正在尝试的是:
import tempfile, os, csv
tf = tempfile.NamedTemporaryFile(delete=False)
try:
with open(tf.name, 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',')
csvwriter.writerows(resources)
except Exception as e:
LOG.error(e)
try:
with open(tf.name, 'r') as f:
files = {'attachment': ('some.csv',
f, 'text/csv')}
try:
retval = group.file_upload(payload=payload, files=files)
except Exception as e:
LOG.error(e)
except Exception as e:
LOG.error(e)
print(tf.name)
tf.close()
# os.remove(tf.name)
但是 tf.close 没有删除文件...
os.remove 抛出错误 PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
有什么办法可以删除这个文件吗?