Skip to main content
 首页 » 编程设计

python之打开并读取以空格分隔的 txt 文件

2025年05月04日21www_RR

我有一个空格分隔的 txt 文件,如下所示:

2004          Temperature for KATHMANDU AIRPORT        
        Tmax  Tmin 
     1  18.8   2.4  
     2  19.0   1.1  
     3  18.3   1.7  
     4  18.3   1.0  
     5  17.8   1.3  

我想分别计算 Tmax 和 Tmin 的平均值。但是,我很难阅读 txt 文件。我试过 this link like .

import re 
list_b = [] 
list_d = [] 
 
with open('TA103019.95.txt', 'r') as f: 
    for line in f: 
        list_line = re.findall(r"[\d.\d+']+", line) 
        list_b.append(float(list_line[1])) #appends second column 
        list_d.append(float(list_line[3])) #appends fourth column 
 
print list_b 
print list_d 

但是,它给我错误: IndexError:列表索引超出范围 这里有什么问题?

请您参考如下方法:

解决这个问题的一个简单方法是使用 split()功能。 当然,你需要去掉前两行:

with io.open("path/to/file.txt", mode="r", encoding="utf-8") as f: 
    next(f) 
    next(f) 
    for line in f: 
        print(line.split()) 

你得到:

['1', '18.8', '2.4'] 
['2', '19.0', '1.1'] 
['3', '18.3', '1.7'] 
['4', '18.3', '1.0'] 
['5', '17.8', '1.3'] 

引用文档:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.