【发布时间】:2019-06-25 04:49:47
【问题描述】:
我正在尝试使用 Python 合并来自不同 .dat 文件的内容。这些文件都具有相同的名称:
taueq_polymer_substratechain1600_12_raf2_000_B0_20_S5_0.dat
但位于包含其他 .dat 文件的不同文件夹中。
文件内容如下形式:File Content(两列)。
我正在尝试将所有这些文件合并到一个文本文件中,其中每两列将彼此相邻。与此类似的内容:Desired Output 但在文本文件中。
我在这里找到了一些帮助:How to merge content from files with same name but in different folders by Python?
但是使用此代码:
import os
# create a dictionary with file names as keys
# and for each file name the paths where they
# were found
file_paths = {}
for root, dirs, files in os.walk('.'):
for f in files:
if f.startswith('taueq_polymer'):
if f not in file_paths:
file_paths[f] = []
file_paths[f].append(root)
# for each file in the dictionary, concatenate
# the content of the files in each directory
# and write the merged content into a file
# with the same name at the top directory
for f, paths in file_paths.items():
txt = []
for p in paths:
with open(os.path.join(p, f)) as f2:
txt.append(f2.read())
with open(f, 'w') as f3:
f3.write(''.join(txt))
输出文本文件将文件的数据附加在原始文件的底部而不是它旁边。谁能告诉我如何将列堆叠在一起?
谢谢
【问题讨论】:
-
这就是 append 的作用。
标签: python merge text-files