Python读取文本文件不正确

2024-09-27 09:33:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图读入一个类似这样的文本文件:

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

这就是我所拥有的:

^{pr2}$

我这样做的前一个文件,非常类似于这一个,一切顺利。但是,此文件未正确读入。首先,它给我一个错误“list index out of range”(列表索引超出范围)closure_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']

我尝试过重写文本文件,以防某个特定文件有损坏,但它仍然会做同样的事情。我不知道为什么,因为上一次还不错。在

有什么建议吗? 谢谢!在


Tags: 文件内容date错误list文本文件x00closure
2条回答

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

相关问题 更多 >

    热门问题