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

我需要通过比较第一列字符串来从原始注释txt文件(B.txt)中获取20万个注释。

例如:

A.txt就像

00001.jpg

00002.jpg

00004.jpg

...

B.txt就像

00001.jpg 12 3 1 33

00002.jpg 32 4 2 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 2

00004.jpg 3 5 3 1

...

我担心的代码似乎无法在C.txt中写任何行

.container {
  position: relative;
  background: #ccc;
  width: 500px;
  height: 1500px;
  padding: 15px;
}

img {
  position: fixed;
}
xuxianbing11 回答:如何将两个txt文件中具有相同列的数据转换为新的txt?

您的代码不起作用,因为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')
本文链接:https://www.f2er.com/3154025.html

大家都在问