我在我的主程序中有以下代码:
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我想返回一个列表,每个值都在文本文件的右栏中。但是当我打印(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为什么只有第一行存储在列表中?代码中的错误是什么?我找不到它..。
发布于 2021-11-23 10:09:46
使用不带参数的.split()将在所有空格上拆分行。这也会去掉末尾的换行符。因此,您可以将代码简化为:
def readfile(file):
with open(file, encoding="utf-8") as file:
list = []
for row in file:
temp = row.split()
list.append(temp[1])
return list发布于 2021-11-23 10:10:14
这是您需要的更改:在空格上使用split,而不是在\t上,请参阅以下更新后的代码。此外,永远不要使用list等内置的变量名
def readfile(file):
with open(file, encoding="utf-8") as file:
out_list = []
for row in file:
temp = row.split() # Split on space rather than \t
temp[1] = temp[1].strip()
out_list.append(temp[1])
return out_list发布于 2021-11-23 10:23:32
您可以使用列表理解方法。
def readfile(file):
with open(file, encoding="utf-8") as file:
return [row.split()[1] for row in file]输出
['2348.84', '2330.13', '2344.20', '2323.17', '2313.24', '2290.85', '2302.26', '2302.67', '2317.67', '2330.07', '2324.90', '2331.84', '2327.12', '2331.42', '2346.46', '2365.45', '2374.47', '2385.63', '2384.10', '2373.04', '2373.92', '2368.71']https://stackoverflow.com/questions/70078887
复制相似问题