【发布时间】:2017-03-30 20:43:05
【问题描述】:
我正在尝试在 Python 中打开一个 .txt 文件。
在将其标记为重复之前,请查看以下代码和文件。
我以前用这个sn-p读取过类似的文件,但是这批文件不起作用。
location="sample/sample2/"
filename=location+"Detector_-3000um.txt"
skip=25 #Skip the first 25 lines
打开它的代码是 -
f=open(filename)
num_lines = sum(1 for line in f)
print "Skipping the first "+str(skip)+" lines"
data=np.zeros((num_lines-skip+1,num_lines-skip+1))
f.close()
f=open(filename)
i=0
for _ in range(skip): #skip unwanted rows
next(f)
for line in f:
data[i,:]=line.split()
i+=1
f.close()
它是一个 501x501 的数据集,第一行和第一列分别是行号和列号。
数据集附here。
我也尝试使用 panda - pd.read_csv(filename,skiprows) 但是它给出了这个错误 -
CParserError: Error tokenizing data. C error: Expected 1 fields in line 49, saw 501
【问题讨论】:
-
“有时此代码不起作用”不是问题。
-
with open(filename) as f:加上f.seek(0)回到开始会大大清理这个问题。 -
您在
f.close()之前f=open(filename)之前的任何具体原因? -
f.close() 重置计数器。最初的一组是计算行数,然后下一组是读取文件。
-
在使用 pandas 方面我建议你看看这个:stackoverflow.com/questions/18039057/…