Python 将多个文本文件中的特定列合并到一个文件中
我有多个文件夹,每个文件夹中都有一个文本文件(Python 将多个文本文件中的特定列合并到一个文件中,python,Python,我有多个文件夹,每个文件夹中都有一个文本文件(input.txt)。首先,我从f_names.txt中读取文件夹名称,然后进入每个文件夹并从每个文件夹的input.txt中读取第三列。在此之前,代码正常工作。问题是代码合并了输出文件中一行中的所有第三列(combine.txt)。而我希望将第三列作为新列写入输出文件(combine.txt)。我该怎么做 这是我的代码: #!/usr/bin/python import os import re path=os.getcwd() try:
input.txt
)。首先,我从f_names.txt
中读取文件夹名称,然后进入每个文件夹并从每个文件夹的input.txt
中读取第三列。在此之前,代码正常工作。问题是代码合并了输出文件中一行中的所有第三列(combine.txt
)。而我希望将第三列作为新列写入输出文件(combine.txt
)。我该怎么做
这是我的代码:
#!/usr/bin/python
import os
import re
path=os.getcwd()
try:
os.remove("combine.txt")
except OSError:
pass
with open('combine.txt', mode='a') as outfile:
with open('f_names.txt', 'r') as read_f:
for line in read_f:
os.chdir(line.strip())
with open('input.txt', 'r') as f:
data=[]
for line in f:
row = line.split()
data.append(float(row[2]))
outfile.write("%.2f\n" % float(row[2]))
os.chdir("..")
2.12
3.15
4.18
8.45
2.10
0.12
0.18
0.32
0.21
0.13
2.12 0.12
3.15 0.18
4.18 0.32
8.45 0.21
2.10 0.13
获得的输出(对于两个输入文件):
#!/usr/bin/python
import os
import re
path=os.getcwd()
try:
os.remove("combine.txt")
except OSError:
pass
with open('combine.txt', mode='a') as outfile:
with open('f_names.txt', 'r') as read_f:
for line in read_f:
os.chdir(line.strip())
with open('input.txt', 'r') as f:
data=[]
for line in f:
row = line.split()
data.append(float(row[2]))
outfile.write("%.2f\n" % float(row[2]))
os.chdir("..")
2.12
3.15
4.18
8.45
2.10
0.12
0.18
0.32
0.21
0.13
2.12 0.12
3.15 0.18
4.18 0.32
8.45 0.21
2.10 0.13
所需输出(用于两个输入文件):
#!/usr/bin/python
import os
import re
path=os.getcwd()
try:
os.remove("combine.txt")
except OSError:
pass
with open('combine.txt', mode='a') as outfile:
with open('f_names.txt', 'r') as read_f:
for line in read_f:
os.chdir(line.strip())
with open('input.txt', 'r') as f:
data=[]
for line in f:
row = line.split()
data.append(float(row[2]))
outfile.write("%.2f\n" % float(row[2]))
os.chdir("..")
2.12
3.15
4.18
8.45
2.10
0.12
0.18
0.32
0.21
0.13
2.12 0.12
3.15 0.18
4.18 0.32
8.45 0.21
2.10 0.13
您可以做一些事情来使您的程序正确并且“更具pythonic”
谢谢在每个
input.txt
文件中还有两行以@
和#
符号开头。如何在每个输入文件中排除这些行?