简体   繁体   中英

Python csv.DictReader

I was trying different codes with csv.DictReader to read csv file into a variable.

#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?
  2. Why is reader needed in option 2 for this code to work?
  3. Some codes I've seen doesn't include "r" but still work the same. 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

  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

    dna = list(csv.DictReader(file))
  3. r mode for read, is the default one, so put or not is same

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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