我有一些文本文件,其中每个文件都有 90 列长度不同的时间序列数据。在这90列之前,有6行垃圾字符串数据我要删除。从第 7 行开始,数据都是 float 类型。
我已尝试以下操作,但它没有更改我的文件:
folder = '/Users/LR/Desktop/S2'
files = os.listdir(folder)
for filename in files:
lines = open(filename).readlines()
open(filename, 'w').writelines(lines[6:])
我还尝试加载文件并跳过前 6 行,但 numpy.loadtxt 不起作用,除非我设置 dtype = 'str'。它成功地剪切了前 6 行..但它作为字符串 ndarray 对象导入,我不知道如何将其转换为 float 组。
data = np.loadtxt('STS2.txt', delimiter = '\t', skiprows=6, dtype='str')
data = data.astype(float) # this gives the error: ValueError: could not convert string to float:
当我设置 dtype = float 时,我得到相同的 ValueError:
data_float = np.loadtxt('STS2.txt', delimiter='\t', dtype=float, skiprows=7) # this gives the error: ValueError: could not convert string to float:
有人知道解决这个问题的方法吗?
最佳答案
每行的最后一个字段是空字符串,因此 numpy 无法将其解析为浮点型。无论如何,您只对前 90 列感兴趣,因此添加 usecols=range(90)
:
np.loadtxt('STS2.txt', skiprows=6, usecols=range(90))
(当然,如果您已经砍掉了前六行,现在可以删除 skiprows=6
。)
编辑
由于第一列似乎只是一个索引,因此您可以使用 usecols=range(1, 90)
忽略它。
关于python:循环遍历txt文件并删除前几行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46571187/