python无法正确读取文本文件

python无法正确读取文本文件,python,text-files,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.

我正在尝试读取一个文本文件,该文件如下所示:

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\u starttime.append(str(data1[1]))
提供了一个错误“列表索引超出范围”,当我要求它打印data1或closure\u date的内容时,它给了我类似的信息

['\x006\x00/\x008\x00/\x001\x004\x00,\x00 \x001\x008\x003\x002\x00,\x00 \x001\x009\x000\x003\x00\r\x00\n']
我已经尝试过重写文本文件,以防该文件有损坏,但它仍然会做同样的事情。我不知道为什么,因为上次这个很好用

有什么建议吗?
谢谢

这看起来像是一个使用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)
试试这个

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]))

看看print(repr(g))给了你什么?每行前面有空格吗?我对格式做了一些修改,但对项目符号做了一些假设。。实际文件中没有破折号,对吗?嗯。。。看起来每个字符都有两个字节宽。每行前后都没有空格。是的,这很有效,谢谢!对不起,我是个业余程序员,所以这对我来说有点陌生。然后跳过头一行?@Melinda:这就是为什么他有一行
g.next()#跳过头一行
。它也可以写入
next(g)