【问题标题】:Open .txt file in Python after skipping lines - Encoding issue跳过行后在 Python 中打开 .txt 文件 - 编码问题
【发布时间】: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/…

标签: python encoding


【解决方案1】:

我认为,您的代码没有问题,问题在于文件编码。

我将您的文件编码转换为“utf-8”,然后您的代码和 pandas 中的 read_csv() 都可以正常工作。

pd.read_csv(myfile, skiprows=24, header=0, index_col=0,sep='\t')

编码转换的方式有很多,比如使用notepad++(windows),我做的方式或者请看这里:How to convert a file to utf-8 in Python?

【讨论】:

  • 就是这样。在转换文件工作。为了将来参考,什么可以指示编码问题?基本上我应该注意什么?有简单的功能检查吗?
  • @shbhuk 我会在开头添加一个检查:1)找出代码是否是“utf-8”编码的。 2)如果不是,那么我将其转换为“utf-8”,否则继续。我认为,这应该是最简单的方法。 Hier 是关于如何做到这一点的帖子:stackoverflow.com/questions/6707657/…
  • 您可以使用 chardet 之类的东西来自动进行编码检测。它通常会完成这项工作,但可能会出现一些极端情况,您会得到错误的结果。当您知道正确的编码时,您可以将其传递给 open 函数。 with open(filename, encoding='ascii') as src:
猜你喜欢
  • 2012-04-19
  • 2017-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多