【发布时间】:2018-03-16 05:17:42
【问题描述】:
我有文本文件,其中每个文件都有 90 列长度不同的时间序列数据。在这 90 列之前,我要删除 6 行垃圾字符串数据。从第 7 行开始,数据都是浮点类型。
我尝试了以下方法,但对我的文件没有任何改变:
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 对象导入,我不知道如何将其转换为浮点数组。
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:
有人知道解决这个问题的方法吗?
【问题讨论】:
-
你可能想使用
os.path.join(folder, filename)。 -
我应该在哪里将它添加到我的代码中?抱歉,我是 python 和一般编码的新手
-
open(os.path.join(folder, filename))和open(os.path.join(folder, filename), 'w') -
这有助于删除前 6 行,谢谢!但是当我尝试读取文本文件时,我仍然得到相同的值错误:无法将字符串转换为浮点数,即使数据只是数字
-
我认为您必须至少分享该文件的部分内容以供任何人帮助。
标签: python numpy text valueerror