python没有正确读取文本文件

时间:2015-06-24 16:04:38

标签: python text-files

我试图阅读一个看起来像这样的文本文件:

Date, StartTime, EndTime 
6/8/14, 1832, 1903
6/8/14, 1912, 1918
6/9/14, 1703, 1708
6/9/14, 1713, 1750

这就是我所拥有的:

g = open('Observed_closure_info.txt', 'r')
closure_date=[]
closure_starttime=[]
closure_endtime=[]
file_data1 = g.readlines()
for line in file_data1[1:]:
    data1=line.split(', ')
    closure_date.append(str(data1[0]))
    closure_starttime.append(str(data1[1]))
    closure_endtime.append(str(data1[2]))

我是这样做的,以前的文件非常类似于这个,一切正常。但是,此文件未正确读取。首先它给了我一个错误"列表索引超出范围"对于closure_starttime.append(str(data1[1])),当我要求它打印它对data1或closure_date的内容时,它给了我类似的东西

['\x006\x00/\x008\x00/\x001\x004\x00,\x00 \x001\x008\x003\x002\x00,\x00 \x001\x009\x000\x003\x00\r\x00\n']

我已尝试重写文本文件,以防该特定文件出现损坏,但它仍然会做同样的事情。我不确定为什么,因为上次这个工作正常。

有什么建议吗? 谢谢!

2 个答案:

答案 0 :(得分:6)

这看起来像带有UTF-16编码的逗号分隔文件(因此\x00空字节)。您必须解码来自UTF-16的输入,如下所示:

import codecs

closure_date=[]
closure_starttime=[]
closure_endtime=[]
with codecs.open('Observed_closure_info.txt', 'r', 'utf-16-le') as g:
    g.next() # skip header line
    for line in g:
        date, start, end = line.strip().split(', ')
        closure_date.append(date)
        closure_starttime.append(start)
        closure_endtime.append(end)

答案 1 :(得分:1)

试试这个

g = open('Observed_closure_info.txt', 'r')
closure_date=[]
closure_starttime=[]
closure_endtime=[]
file_data1 = g.readlines()
for line in file_data1[1:]:
    data1=line.decode('utf-16').split(',')
    closure_date.append(str(data1[0]))
    closure_starttime.append(str(data1[1]))
    closure_endtime.append(str(data1[2]))