我如何跳过标题行并开始从第2行读取文件?


当前回答

f = open(fname).readlines()
firstLine = f.pop(0) #removes the first line
for line in f:
    ...

其他回答

如果你想要第一行,然后你想对文件执行一些操作,这段代码将会很有帮助。

with open(filename , 'r') as f:
    first_line = f.readline()
    for line in f:
            # Perform some operations

如果您想从第2行开始读取多个CSV文件,这就像一个魅力

for files in csv_file_list:
        with open(files, 'r') as r: 
            next(r)                  #skip headers             
            rr = csv.reader(r)
            for row in rr:
                #do something

(这是Parfait对另一个问题的部分回答)

如果切片可以在迭代器上工作……

from itertools import islice
with open(fname) as f:
    for line in islice(f, 1, None):
        pass
f = open(fname).readlines()
firstLine = f.pop(0) #removes the first line
for line in f:
    ...
with open(fname) as f:
    next(f)
    for line in f:
        #do something