Python 在一行中写入以前未知数量的数据
我有大量的文件,我想从中提取数据并写入文件。示例输入行是:Python 在一行中写入以前未知数量的数据,python,Python,我有大量的文件,我想从中提取数据并写入文件。示例输入行是: species,subl,cmp= 1 6 1 s1,torque= 0.11616E-06-0.50264E-14 species,subl,cmp= 2 6 1 s1,torque= 0.13407E-03 0.74778E-07 species,subl,cmp= 3 6 1 s1,torque= 0.71246E-06 0.28390E-14 spe
species,subl,cmp= 1 6 1 s1,torque= 0.11616E-06-0.50264E-14
species,subl,cmp= 2 6 1 s1,torque= 0.13407E-03 0.74778E-07
species,subl,cmp= 3 6 1 s1,torque= 0.71246E-06 0.28390E-14
species,subl,cmp= 3 6 3 s1,torque=-0.46230E-12 0.30428E-13
一个给定的文件很少有这样的行,我想写在一行中
这个小脚本显示了我的意图
#!/usr/bin/python3
import sys
# import math
import os
rootdir = str(sys.argv[1])
outf = str(sys.argv[2])
s = []
with open(outf, 'w') as of1:
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file == "out-Dy-eos2":
inf = subdir+'/'+file
with open(inf, 'r') as inf1:
for line in inf1:
if "species,subl,cmp=" in line:
of1.write(line[-13:])
# s.append(line[-13:])
# print(s)
它以新行给出每个输出,如下所示:
-0.50264E-14
0.74778E-07
0.28390E-14
依此类推,也就是说,每个条目都有一个新行
我还尝试添加一个列表,如下所示(请不要为数字而烦恼):
我假设新行在输入文件本身中。
所以,问题是,我怎样才能把这些值写在同一行?没有换行?这很简单,只需在写入文件之前使用line.rstrip('\n')。这也为您提供了一个按自己的方式格式化的机会。比如说
if "species,subl,cmp=" in line:
data = line[-13:].rstrip('\n')
of1.write(data+" ")
会给你一个看起来像
-0.50264E-14 0.74778E-07 0.28390E-14
您可能正在寻找吗?或者只是of1.write(第[-13:-1行])
-0.50264E-14 0.74778E-07 0.28390E-14