问题描述
我一直在学习python,并尝试使用字典,.csv文件和csv模块。看来 csv.DictReader()
函数可以帮助将.csv文件转换成字典对象,但是我对混淆的Reader对象有些奇怪。
I'm been learning python and playing around with dictionaries and .csv files and the csv module. It seems like the csv.DictReader()
function can help turn .csv files into dictionary objects, but there's a bit of a quirk with the Reader objects that I'm confused about.
我已经阅读了一些文档(然后尝试查找查找 csv.Reader()
函数),但我仍然不确定。
I've read a little bit into the documentation (and then tried to find answers looking up at the csv.Reader()
function), but I'm still a little unsure.
为什么此代码按预期运行:
Why does this code run as expected:
with open("cool_csv.csv") as cool_csv_file:
cool_csv_text = cool_csv_file.read()
print(cool_csv_text)
,但以下代码返回 ValueError:对已关闭文件的I / O操作。
with open("cool_csv.csv") as cool_csv_file:
cool_csv_dict = csv.DictReader(cool_csv_file)
for row in cool_csv_dict:
print(row["Cool Fact"])
因为我们保存了 DictReader
对象到python变量,我们不应该b能够在关闭文件后调用变量,例如是否为我分配了 cool cool_csv.read()
?
Since we saved the DictReader
object to a python variable, shouldn’t we be able to call the variable after we close the file, like if I were assigned cool cool_csv.read()
?
我知道正确的编码方式是:
I know the proper way to code this would be:
with open("cool_csv.csv") as cool_csv_file:
cool_csv_dict = csv.DictReader(cool_csv_file)
for row in cool_csv_dict:
print(row["Cool Fact"])
但是为什么必须在 open()
部分中嵌套cool_csv_dict:部分中的行?
But why does the for row in cool_csv_dict:
section have to be nested in the open()
section?
我唯一的猜测是,因为 csv.DictReader()
对象不是真正的字典(或类似的东西) ,这是一些诡计,因为它仍然需要指向某处(因为这可能就是阅读器部分。)。
My only guess would be that because the csv.DictReader()
object is not quite an actual dictionary (or something like that), there’s some shenanigans because it still needs to point somewhere (because maybe thats the "reader" part?).
任何人都可以见识吗?
推荐答案
<$ c $创建 cool_csv_dict
对象时,c> csv.DictReader 不会将整个文件读入内存。每次调用它从CSV获取下一条记录时,它都会从 cool_csv_file
中读取下一行。因此,它需要保持打开状态,以便可以根据需要读取它。
csv.DictReader
doesn't read the entire file into memory when you create the cool_csv_dict
object. Each time you call it to get the next record from the CSV, it reads the next line from cool_csv_file
. Therefore, it needs this to be kept open so it can read from it as needed.
csv.DictReader
的参数可以是任何返回行的迭代器。因此,如果您不想让文件保持打开状态,可以调用 readlines()
将所有行放入列表中,然后将其传递给 csv.DictReader
The argument to csv.DictReader
can be any iterator that returns lines. So if you don't want to keep the file open, you can call readlines()
to get all the lines into a list, then pass that to csv.DictReader
with open("cool_csv.csv") as cool_csv_file:
cool_csv_lines = cool_csv_file.readlines()
cool_csv_dict = csv.DictReader(cool_csv_lines)
for row in cool_csv_dict:
print(row("Cool Fact")
这篇关于为什么csv DictReader字典对象仅在文件仍处于打开状态时才起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!