Объединение различных текстовых файлов, расположенных в разных папках, с помощью Python - PullRequest
0 голосов
/ 24 июня 2019

Я пытаюсь объединить контент из разных файлов .dat, используя Python. Все эти файлы имеют одинаковые имена:

taueq_polymer_substratechain1600_12_raf2_000_B0_20_S5_0.dat

но находятся внутри разных папок, в которых находятся другие файлы .dat.

Содержимое файлов имеет следующий вид: Содержимое файла (два столбца).

Я пытаюсь объединить все эти файлы в один текстовый файл, где каждые два столбца будут расположены рядом друг с другом. Нечто похожее на это: Желаемый вывод но в текстовом файле.

Я нашел некоторую помощь здесь: Как объединить содержимое из файлов с одинаковыми именами, но в разных папках с помощью 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))

В выходной текстовый файл добавляются данные файлов внизу исходного файла, а не рядом с ним. Может кто-нибудь сказать мне, как сложить столбцы рядом друг с другом?

Спасибо

1 Ответ

0 голосов
/ 24 июня 2019

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))
...