使用 Python 合并两个文本文件
我尝试迭代两个不同的文本文件,并根据两个文件中每一行开头找到的帐号创建一个合并文件。我首先读取包含报表数据的主文件并读取每一行,直到找到与前一行不匹配的帐号,然后开始迭代第二个文件并尝试将任何匹配的帐号与前一行相匹配文件 1 中的块。当我到达这一部分时,我遇到了麻烦。
一些示例数据为:
File1 .... File2
000990 000990 是我的伙伴
000990 000990 是我的伙伴
000760 000530 是我的伙伴
000760 000530 是我的伙伴
000530 000999 是我的伙伴
000530 000999 是我的伙伴
000999
所需输出
000990
000990
000990是我的伙伴
000990是我的伙伴
000760
000760
000530
000530
000530是我的伙伴
000530是我的伙伴
000999
000999是我的伙伴
000999 是我的伙伴
这是我到目前为止尝试过的代码。任何帮助或建议将不胜感激。 谢谢
x=open('testaccount.txt')
y=open('accountpartner.txt')
count=1
inv_count=1
for line in x:
if count==1:
a=x.readline()
print('S'+line, end='')
if line[0:6]==a[0:6]:
print('S'+line, end='')
elif line[0:6]!=a[0:6]:
for inv_line in y:
if inv_count==1:
b=y.readline()
if b[0:6]==a[0:6]:
print('I',b,end='')
inv_count+=1
print('break')
print('S'+line,end='')
a=line
count=1
continue
count+=1
print('this is a',a)
Im trying to iterate through two different text files and create one consolidated file based on the account number found at the beginning of each line in both files. I begin by reading the main file which contains statement data and read each line until I find an account number that doesn't match the previous line, I then start iterating through the second file and try to match up any matching account numbers with the previous block from file 1. I am having trouble when I get to this part.
Some sample data would be:
File1 .... File2
000990 000990 is my partner
000990 000990 is my partner
000760 000530 is my partner
000760 000530 is my partner
000530 000999 is my partner
000530 000999 is my partner
000999
Desired Output
000990
000990
000990 is my partner
000990 is my partner
000760
000760
000530
000530
000530 is my partner
000530 is my partner
000999
000999 is my partner
000999 is my partner
This is the code I have tried so far. Any help or suggestions would be greatly appreciated.
Thanks
x=open('testaccount.txt')
y=open('accountpartner.txt')
count=1
inv_count=1
for line in x:
if count==1:
a=x.readline()
print('S'+line, end='')
if line[0:6]==a[0:6]:
print('S'+line, end='')
elif line[0:6]!=a[0:6]:
for inv_line in y:
if inv_count==1:
b=y.readline()
if b[0:6]==a[0:6]:
print('I',b,end='')
inv_count+=1
print('break')
print('S'+line,end='')
a=line
count=1
continue
count+=1
print('this is a',a)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为此使用词典。这比编写自己的排序合并要简单得多。
Use dictionaries for this. It's much simpler that writing your own sort-merge.