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

标签 python csv

我有一个空格分隔的 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.

关于python - 打开并读取以空格分隔的 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54507444/

相关文章:

python - 不使用特殊字符在python中加密和解密

Python Pandas 选择指数大于 x 的指数

python - wxpython 中可调整大小的分隔线?

Java 将计算列添加到 CSV 文件

Python/Pandas - 基于多个条件的新列

python - pandas 日期时间格式转换

csv - 上下文输出到CSV文件

python - 使用Python修改csv中的特定列

python - Pandas 用字符串转换日期

java - 使用 Hibernate 将 csv 文件导入 MySQL 数据库