【发布时间】:2019-05-15 01:12:47
【问题描述】:
我正在通过从 S3 下载文件来写入临时文件。当我在我的文本编辑器中打开下载的文件(称为3)时,我可以看到所有的文本行。但是当我尝试逐行读取文件时,我的代码没有返回任何内容。
运行代码后,临时文件在Python脚本目录下创建,不会消失。
import tempfile
import os
import boto3
s3 = boto3.client('s3')
with tempfile.TemporaryFile() as tf:
try:
s3.download_file(
Bucket='the-chumiest-bucket',
Key='path/to/the/file.txt',
Filename=str(tf.name)
)
except Exception as e:
print('error:', e)
tf.flush()
tf.seek(0, os.SEEK_END)
for line in tf.readlines():
print('line:', line)
如果我跑步
with open('3', 'r') as f:
for line in f.readlines():
print(line)
我得到了这些行,所以这可能是一种解决方法,但我看到很多人使用这种确切的方法从临时文件中读取行。
预期结果:
我打印了file.txt 中的行。
实际结果:
我什么也没打印出来。
编辑#1
将tf.seek(0, os.SEEK_END) 更改为tf.seek(0, os.SEEK_SET)(感谢@Barmar),仍然没有打印行。只有一个空行。
【问题讨论】:
-
您正在使用
SEEK_END查找文件末尾。在那之后没有数据可以读取。 -
也许你应该直接下载到一个对象而不是下载到一个文件。见stackoverflow.com/questions/37087203/…
-
尝试使用
tempfile.NamedTemporaryFile(),因为tempfile.TemporaryFile()返回的不是真实文件(只是“类文件”对象)。