【发布时间】:2021-11-23 18:36:04
【问题描述】:
我的主程序中有这段代码:
def readfile(file):
with open(file, encoding="utf-8") as file:
list = []
for row in file:
temp = row.split("\t")
temp[1] = temp[1].strip()
list.append(temp)
return list
我想读取这种格式的 txt 文件:
21-10-22 2348.84
21-10-25 2330.13
21-10-26 2344.20
21-10-27 2323.17
21-10-28 2313.24
21-10-29 2290.85
21-11-01 2302.26
21-11-02 2302.67
21-11-03 2317.67
21-11-04 2330.07
21-11-05 2324.90
21-11-08 2331.84
21-11-09 2327.12
21-11-10 2331.42
21-11-11 2346.46
21-11-12 2365.45
21-11-15 2374.47
21-11-16 2385.63
21-11-17 2384.10
21-11-18 2373.04
21-11-19 2373.92
21-11-22 2368.71
我想返回一个列表,其中包含文本文件右侧列中的每个值。但是当我做 print(readfile("file.txt")) 它只是打印 "['21-10-22 2348.84\n']" 然后
Traceback (most recent call last):
File "main.py", line 51, in readfile
temp[1] = temp[1].strip()
IndexError: list index out of range
为什么只有第一行存储在列表中?代码中的错误是什么?没找到……
【问题讨论】:
-
看起来至少其中一行不包含 \t 字符,因此
row.split("\t")返回长度为 1 的列表。这意味着temp[1]不存在。 -
你确定有标签吗?异常在第一行引发。
-
好吧,给出的示例文本文件没有制表符,但双倍空格作为分隔符。要么更改文本文件以使用选项卡,要么只使用 row.split() 并查看。
-
这能回答你的问题吗? Python: Splitting txt file by tab
标签: python