[英]Why is using .reader() skipping the first line and .readlines() isn't?
I am attempting to read in all the data from a .csv file. 我正在尝试从.csv文件中读取所有数据。 First, I tried using csv.reader(), but this would skip the first line of my file.
首先,我尝试使用csv.reader(),但这将跳过文件的第一行。 I was able to remedy this using .readlines(), but I am wondering why this happens with .reader() and would like to make it read my first line.
我可以使用.readlines()对此进行补救,但是我想知道为什么.reader()会发生这种情况,并且想让它读取我的第一行。
import glob
import csv
new_cards = []
path = 'C:\\Users\\zrc\\Desktop\\GCData2\\*.asc'
files = glob.glob(path)
# First Method
for name in files:
with open(name) as f:
for line in f:
reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
for row in reader:
new_cards.append(row)
print(len(new_cards))
# Second Method
for name in files:
with open(name) as f:
m = f.readlines()
for line in m:
new_cards.append(line)
print(len(new_cards))
In your first function you dont need to use for line in f:
this line is taking your first line and then the reader starts from the second. 在您的第一个函数中,您无需
for line in f:
使用for line in f:
该行占据了您的第一行,然后读者从第二行开始。
The correct way should be: 正确的方法应该是:
for name in files:
with open(name) as f:
reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
for row in reader:
new_cards.append(row)
print(len(new_cards))
You dont need to iterate over each line in the first one because you are already doing it with for row in reader:
您不需要遍历第一行中的每一行,因为您已经
for row in reader:
使用了for row in reader:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.