gpt4 book ai didi

python 没有正确读取文本文件

转载 作者:太空狗 更新时间:2023-10-29 22:29:57 27 4
gpt4 key购买 nike

我正在尝试读取如下所示的文本文件:

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])) 提供了一个错误“list index out of range”,当我要求它打印 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']

我已经尝试重写文本文件以防该特定文件出现损坏,但它仍然做同样的事情。我不确定为什么,因为上次效果很好。

有什么建议吗?谢谢!

最佳答案

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

关于python 没有正确读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31031520/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com