从第2行读取文件或跳过标题行
我怎样才能跳过标题行,并开始从line2读取文件?
with open(fname) as f: next(f) for line in f: #do something
f = open(fname,'r') lines = f.readlines()[1:] f.close()
如果你想要第一行,然后你想对文件执行一些操作,这段代码将会有帮助。
with open(filename , 'r') as f: first_line = f.readline() for line in f: # Perform some operations
f = open(fname).readlines() firstLine = f.pop(0) #removes the first line for line in f: ...
with open('old.csv', 'r') as f, open('new.csv', 'w') as ff: first_line = f.readline() for line in f: line = line.translate({ord(i):None for i in 'abcd'}) ff.write(line) ff.seek(0) ff.write(first_line)
如果切片可以在迭代器上工作…
from itertools import islice with open(fname) as f: for line in islice(f, 1, None): pass