【问题标题】:Merging different text files located in different folders using Python使用 Python 合并位于不同文件夹中的不同文本文件
【发布时间】: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))

输出文本文件将文件的数据附加在原始文件的底部而不是它旁边。谁能告诉我如何将列堆叠在一起?

谢谢

【问题讨论】:

标签: python merge text-files


【解决方案1】:

file1.txt

1.2 1.2
1.3 1.3
1.3 1.3

file2.txt

8.2 8.2
8.3 8.3
8.3 8.3

你除了的结果是:

out.txt

1.2 1.2 8.2 8.2
1.3 1.3 8.3 8.3
1.3 1.3 8.3 8.3

所以你必须逐行读取文件并将它们之间的行连接起来。

paths = 'file1.txt', 'file2.txt'
txt_lines = []
for p in paths:
    with open(p) as f:
        # Iterate through lines.
        for i, line in enumerate(f):
            if line.endswith("\n"):
                # remove the trailing newline
                line = line[:-1]
            try:
                # Concat the line with previous ones of the same index
                txt_lines[i] += ' ' + line
            except IndexError:
                # If the index not exists, append the line to the list
                txt_lines.append(line)
with open('out.txt', 'w') as f:
    # Join each line
    f.write('\n'.join(txt_lines))

【讨论】:

  • 谢谢,如何更改第一行以便程序进入各个文件夹并获取正确的文本文件?
  • 您可以继续按照您在代码中所做的操作。我简化了示例,因为我认为您对其余部分没有任何问题。
猜你喜欢
  • 2022-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
  • 1970-01-01
  • 2013-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多