![](/img/trans.png)
[英]Skipping over the first line of a text file using readlines() in python
[英]Why is using .reader() skipping the first line and .readlines() isn't?
我正在尝试从.csv文件中读取所有数据。 首先,我尝试使用csv.reader(),但这将跳过文件的第一行。 我可以使用.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))
在您的第一个函数中,您无需for line in f:
使用for line in f:
该行占据了您的第一行,然后读者从第二行开始。
正确的方法应该是:
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))
您不需要遍历第一行中的每一行,因为您已经for row in reader:
使用了for row in reader:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.