python - 属性错误 : 'file' object has no attribute 'DictReader'

标签 python csv dictionary temporary-files

我正在创建一个临时 CSV 文件:

for formname in formnamesFinal:
    csv = tempfile.NamedTemporaryFile("w", prefix=formname+'_', suffix=".csv", dir = "/var/tmp/")
csv.write(....)

我正在其中写一些东西。现在我想用 DictReader 阅读这个文件:

content = csv.DictReader(csv, delimiter=';')
for contenthelp in content:
    contentlist.append(contenthelp)

但我收到以下错误:

AttributeError: 'file' object has no attribute 'DictReader'

我必须遍历临时 CSV 文件,因为我有大量数据集要从数据库中获取以用于后续步骤,而且一遍又一遍地加载数据会花费太多时间。

最佳答案

csv = tempfile.NamedTemporaryFile("w", prefix=formname+'_', suffix=".csv", dir = "/var/tmp/")

此行将覆盖您对 csv 模块的引用。尝试将其重命名为其他名称。

my_csv = tempfile.NamedTemporaryFile("w", prefix=formname+'_', suffix=".csv", dir = "/var/tmp/")

现在您应该能够再次正确访问 csv

关于python - 属性错误 : 'file' object has no attribute 'DictReader' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25186358/

相关文章:

python - 如何按列的绝对值对numpy数组进行排序?

python - ndb 模型 - 检索有序的属性名称集

php - 通过 PHP 设置使用 CSV 数据的表中行的样式

java - 如何让 entrySet() 在新行显示键值对?(java)

c# - LINQ 从字典中获取第一项不为空或为空

ios - Spotify 返回无效的 NSDictionary

python - 使用 Enum 的定义顺序作为自然顺序

python - tensorflow : result of training data(using sigmoid) came out reversely

python - 为什么 Python 子进程本地的对象分配会增加 main 的堆大小?

Python 条件不起作用,其中包括 ifelse 子句