如何使用自定义格式使用 python 合并 2 个文件

How to combine 2 files using python using custom format

with open('file_1.txt', 'r') as file :
    filedata_s = file.read()
with open('file_2.txt', 'r') as file :
    filedata_d = file.read()
print (filedata_s+filedata_d)

文件 1 包含 name\age\occupation...等文件 2 包含 Bob\student... 期望的输出是

Name :- ‘Bob’
Age  :- '16'
Occ  :-'student'
              
with open('file_3.txt', 'w') as file_3:
    with open('file_1.txt', 'r') as file_1:
        with open('file_2.txt', 'r') as file_2:
            for line1, line2 in zip(file_1, file_2):
                print(line1.strip(), line2.strip(), file=file_3)
def read_list(filename):
    result = []
    with open(filename, 'r') as file:
        lines = file.readlines()
        for line in lines:
            result.append(line.strip())
    return result


list_s = read_list('file_1.txt')
list_d = read_list('file_2.txt')

for item in zip(list_s, list_d):
    print(item)

假设:输入文件看起来像

name/age/occupation
Bob/16/student

如果您不关心输出中的填充,您可以尝试:

with open('file_1.txt', 'r') as file1, open('file_2.txt', 'r') as file2:
    for line1, line2 in zip(
        file1.read().rstrip().split("/"), file2.read().rstrip().split("/")
    ):
        print(f"{line1} :- '{line2}'")

输出看起来像:

name :- 'Bob'
age :- '16'
occupation :- 'student'

如果要将其写入新文件:

with open('file_1.txt', 'r') as fin1, open('file_2.txt', 'r') as fin2,\
     open('file_3.txt', 'w') as fout:
    fout.writelines(
        f"{line1} :- '{line2}'\n"
        for line1, line2 in zip(
            fin1.read().rstrip().split("/"), fin2.read().rstrip().split("/")
        )
    )

如果你关心填充,你可以尝试:

lines = []
for filename in ('file_1.txt', 'file_2.txt'):
    with open(filename, 'r') as file:
        lines.append(file.read().rstrip().split("/"))
padding = max(map(len, lines[0]))
for line1, line2 in zip(*lines):
    print(f"{line1.ljust(padding)} :- '{line2}'")

输出看起来像:

name       :- 'Bob'
age        :- '16'
occupation :- 'student'

这里你必须评估第一个文件拳头并使用 padding = max(map(len, lines[0])) 来确定最大字符串长度,然后将其与 str.ljust() 一起使用以相应地调整输出。

写入新文件:

...
with open('file_3.txt', 'w') as file:
    file.writelines(
        f"{line1.ljust(padding)} :- '{line2}'\n" for line1, line2 in zip(*lines)
    )

如果你有多条输入线,我会使用标准库中的 csv 模块,比如

import csv

with open("file_1.txt", "r") as fin1, open("file_2.txt", "r") as fin2:
    reader1 = csv.reader(fin1, delimiter="/")
    reader2 = csv.reader(fin2, delimiter="/")
    for row1, row2 in zip(reader1, reader2):
        for item1, item2 in zip(row1, row2):
            print(f"{item1} :- '{item2}'")

或带填充

with open("file_1.txt", "r") as file:
    padding = max(
        len(item) for row in csv.reader(file, delimiter="/") for item in row
    )

with open("file_1.txt", "r") as fin1, open("file_2.txt", "r") as fin2:
    reader1 = csv.reader(fin1, delimiter="/")
    reader2 = csv.reader(fin2, delimiter="/")
    for row1, row2 in zip(reader1, reader2):
        for item1, item2 in zip(row1, row2):
            print(f"{item1.ljust(padding)} :- '{item2}'")