如何将两个txt文件中相同列的数据转换为新的txt文件?

2024-03-29 12:37:35 发布

您现在位置:Python中文网/ 问答频道 /正文

通过比较第一列字符串,我需要从原始注释txt文件(B.txt)中获得200000多个注释

例如:

A.txt就像

00001.jpg

00002.jpg

00004.jpg

B.txt就像

00001.jpg 12 3 1 33

00002.jpg 32 4 2

00003.jpg 23 4 5 1

00004.jpg 3 5 3 1

00005.jpg 2 4 1 1

我想要一个C.txt,就像

00001.jpg 12 3 1 33

00002.jpg 32 4 2

00004.jpg 3 5 3 1

我编写的代码似乎无法用C.txt编写任何行

alines = open('A.txt', 'r').readlines() 
blines = open('B.txt', 'r').readlines()
fw = open('C.txt', 'w')
for al in alines:
    for bl in blines:
        if str(al) in str(bl):
            fw.write(bl)
fw.close()

Tags: 文件字符串代码intxtforopenjpg
1条回答
网友
1楼 · 发布于 2024-03-29 12:37:35

代码不起作用,因为alinesblines列表包含以“\n”符号结尾的行,因此比较总是失败

以下代码去除“\n”符号,并消除第二个“for”循环:

with open('A.txt', 'r') as fh:
    # Splitlines gets rid of the '\n' endlines
    alines = fh.read().splitlines()
with open('B.txt', 'r') as fh:
    # Splitlines gets rid of the '\n' endlines
    blines = fh.read().splitlines()
with open('C.txt', 'w') as fh:
    for line in blines:
        # Split the file name
        parts = line.split(' ', 1)
        # Look up the filename
        if parts[0] in alines:
            fh.write(line + '\n')

相关问题 更多 >