社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Sampath • 3 年前 • 1291 次点击  
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包含名称\年龄\职业。。。etc文件2包含Bob\16\student。。。 期望的输出是

Name :- ‘Bob’
Age  :- '16'
Occ  :-'student'
              
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131522
 
1291 次点击  
文章 [ 3 ]  |  最新文章 3 年前
Vasily
Reply   •   1 楼
Vasily    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)
SpawnHeaven Discord
Reply   •   2 楼
SpawnHeaven Discord    3 年前
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)
Timus
Reply   •   3 楼
Timus    3 年前

假设:输入文件看起来像

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}'")