简体   繁体   English

Python csv.DictReader

[英]Python csv.DictReader

I was trying different codes with csv.DictReader to read csv file into a variable.我正在尝试使用 csv.DictReader 使用不同的代码将 csv 文件读入变量。

#option 1
dna = []
with open(sys.argv[1], "r") as file:
    dna = csv.DictReder(file)
print(dna)
#output = csv.DictReader object at 0x123

#option 2
dna = []
with open(sys.argv[1], "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        dna.append(row)
print(dna)
#output = csv in array

I have a few questions about this code.我对这段代码有几个问题。

  1. Why does option 1 return an address?为什么选项 1 返回地址?
  2. Why is reader needed in option 2 for this code to work?为什么在选项 2 中需要阅读器才能使此代码正常工作?
  3. Some codes I've seen doesn't include "r" but still work the same.我见过的一些代码不包含“r”,但仍然可以正常工作。 Why is that?这是为什么?

Thank you!谢谢!

  1. DictReader is a class, when you instantiate it DictReader() you have an instance of that class, which is located somewhere in memory DictReader是一个类,当你实例化它DictReader()你有那个类的一个实例,它位于内存中的某个地方

  2. The class helps you to read the csv, it is designed to gives you the content if you iterate over it, you can so it in one line with该类可以帮助您阅读 csv,它旨在为您提供内容,如果您对其进行迭代,您可以将其与

    dna = list(csv.DictReader(file))
  3. r mode for read, is the default one, so put or not is same r读取模式,是默认模式,所以 put or not 是一样的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM