我有一个文本文件“lines.txt”,如图所示:
0.02 7 433 649 239 32
0.04 84 43 594 2 321
0.06 65 34 94 5 138
0.08 43 56 23 10 432
1.00 2 382 37 29 102
1.20 573 475 82 757 29
Time (s)
Number (unit)
Third (none)
Fourth (none)
Fifth (none)
Test (none)
底部的字符串实际上是上面数据的列名称(从左到右,所以
Time_1 is 0.02
,Number_1 is 7
等)。
我已经使用 .split
函数分割了每个行字符串。我现在希望插入底部 6 个文本字符串作为现在分隔的浮点字符串的列标题。
我如何编写一个函数来分隔两位数据,以便我可以将底部字符串指定为列标题?
到目前为止我已经:
f = open('lines.txt','r')
lines = f.readlines()
for line in lines:
data = line.split()
data1 = line.strip()
print(data)
for line in data:
if data is not object:
data = [float(x) for x in data]
我认为将以数字形式出现的数据转换为浮点数,但当它到达文本字符串(时间(秒))时我无法让它停止读取。任何帮助表示赞赏
如果无法转换该行,请将其另存为标题:
with open('lines.txt') as file:
data = []
headings = []
for line in file:
try:
data.append([float(x) for x in line.split()])
except ValueError:
headings.append(line.strip())
print(headings)
for line in data:
print(line)
输出:
['Time (s)', 'Number (unit)', 'Third (none)', 'Fourth (none)', 'Fifth (none)', 'Test (none)']
[0.02, 7.0, 433.0, 649.0, 239.0, 32.0]
[0.04, 84.0, 43.0, 594.0, 2.0, 321.0]
[0.06, 65.0, 34.0, 94.0, 5.0, 138.0]
[0.08, 43.0, 56.0, 23.0, 10.0, 432.0]
[1.0, 2.0, 382.0, 37.0, 29.0, 102.0]
[1.2, 573.0, 475.0, 82.0, 757.0, 29.0]
要写入 CSV,请添加:
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(headings)
writer.writerows(data)
输出.csv:
Time (s),Number (unit),Third (none),Fourth (none),Fifth (none),Test (none)
0.02,7.0,433.0,649.0,239.0,32.0
0.04,84.0,43.0,594.0,2.0,321.0
0.06,65.0,34.0,94.0,5.0,138.0
0.08,43.0,56.0,23.0,10.0,432.0
1.0,2.0,382.0,37.0,29.0,102.0
1.2,573.0,475.0,82.0,757.0,29.0
希望您需要一个以第 1 行为标题、其余为行的数组
f = open('try.txt','r')
lines = f.readlines()
data={}
cols=[]
# checking each lines and converting all the data to float which is not colomun heading
for index,line in enumerate(lines):
data[index]=[]
for col in line.split():
try:
data[index].append(float(col))
except ValueError:
#if data is not convertable to float add the main line data to cols array
cols.append(line)
break
finalarray = []
for key,value in data.items():
if len(value)==0:
#ignoring the empty dict which represents line for col
continue
else:
#appending lists of float to final array
finalarray.append(value)
#inserting col headings to the index zero
finalarray.insert(0,cols)
#printing final array where line one is col heading and all other lines is rowdata
print(finalarray)