您好,我正在使用 pandas 读取一系列文件并将它们连接到数据框。我的文件开头有一堆垃圾,长度可变,我想忽略。 pd.read_csv() 有 skiprows 方法。我已经编写了一个函数来处理这种情况,但我必须打开文件两次才能使其工作。有没有更好的办法?
HEADER = '#Start'
def header_index(file_name):
with open(file_name) as fp:
for ind, line in enumerate(fp):
if line.startswith(HEADER):
return ind
for row in directories:
path2file = '%s%s%s' % (path2data, row, suffix)
myDF = pd.read_csv(path2file, skiprows=header_index(path2file), header=0, delimiter='\t')
如有任何帮助,我们将不胜感激。
请您参考如下方法:
这现在是可能的(不知道当时是否可能)如下:
pos= 0
oldpos = None
while pos != oldpos: # make sure we stop reading, in case we reach EOF
line= fp.readline()
if line.startswith(HEADER):
# set the read position to the start of the line
# so pandas can read the header
fp.seek(pos)
break
oldpos= pos
pos= fp.tell() # renenber this position as sthe start of the next line
pd.read_csv(fp, ...your options here...)
