[英]Copying selected columns from one file to another
I want to read all columns from the input file and print only selected columns to the output file (0th, 3rd and 2nd column), preserving the header ( 4
and Temperature = 298 K
). 我想从输入文件中读取所有列,并仅将选定的列打印到输出文件(第0、3和2nd列),同时保留标题( 4
和Temperature = 298 K
)。
My current code writes "[1.0, 1.0]" to output file. 我当前的代码将“ [1.0,1.0]”写入输出文件。 How can I fix it? 我该如何解决?
#!/usr/bin/python
with open("test.txt", "r") as f:
a1=[]
a2=[]
a3=[]
a4=[]
for line in f:
if not line.strip() or line.startswith('Temperature') or line.startswith('4'): continue
row = line.split()
a1.append(str(row[0]))
a2.append(float(row[1]))
a3.append(float(row[2]))
a4.append(float(row[3]))
f = open('output.txt','a')
f.write(str(a1)+str(a3)+str(a2))
f.close()
Input file: 输入文件:
4
Temperature = 298 K
C -5.27210 0.23153 0.13488
H -1.99335 -2.87058 3.25594
H -1.33502 -3.88407 1.93295
H -3.06617 -3.39783 1.91314
Requested output: 要求的输出:
4
Temperature = 298 K
C 0.13488 0.23153
H 3.25594 -2.87058
H 1.93295 -3.88407
H 1.91314 -3.39783
I don't quite get why you use four different lists there... You could do it with just one container, like this (not tested): 我不太明白为什么要在其中使用四个不同的列表...您可以只用一个容器来完成此操作,如下所示(未经测试):
#!/usr/bin/python
newlines = []
with open("test.txt", "r") as f:
for line in f:
if not line.strip() or line.startswith('Temperature') or line.startswith('4'): continue
row = line.split()
newlines.append(' '.join([row[0], row[3], row[2]]))
f = open('output.txt','a')
f.write('\n'.join(newlines))
f.close()
How about that? 那个怎么样?
with open('data.txt', 'r') as fin:
with open('data2.txt', 'w') as fout:
# Header
fout.write(fin.readline())
fout.write(fin.readline())
# Columns
for l in fin:
cols = l.split()
fout.write("%s % f % f\n" % (cols[0], float(cols[3]), float(cols[2])))
The code stores only one line of the file at a time and writes to the output file immediately. 该代码一次只存储文件的一行,并立即写入输出文件。 Also, the spacing is preserved as in the original file. 同样,间距保留在原始文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.