我是Python新手。我在这里搜索了其他问题,但没有找到我遇到的确切情况。
我需要能够读取File-A的内容,并从File-B中取出匹配的行。
我知道如何在PowerShell中做到这一点,但是在大文件中它很慢,我正在尝试学习Python。
File-A仅包含贷款号码-每行8到10位数字File-A可以包含1到数千行
File-B可以包含1到数千行,其中包含更多数据,但每行都以相同的8到10位贷款号开头。
我需要在file - a中读取并在file - b中找到匹配的行,并将这些匹配的行写入新文件(都是文本文件)
File-A示例内容-无空格-每行1个贷款
272991
272992
272993
File-B示例内容
272991~20210129~\Serv1LOC7675309867530 16618272991.pdf~0
272992~20210129~\Serv1LOC7675309867530 16618272992.pdf~0
272993~20210129~\Serv1LOC7675309867530 16618272993.pdf~0
是否有人能够帮助我,为我指出正确的方向,或者更好的是,提供一个可行的解决方案?
这是我到目前为止所尝试的,但它所做的只是创建新的pullledloans .txt文件,其中没有任何内容
import os
# os.system('cls')
os.chdir('C:\Temp\')
print(os.getcwd())
# read file
loanFile = 'Loans.txt'
SourceFile = 'Orig.txt'
NewFile = 'PulledLoans.txt'
with open(loanFile, 'r') as content, open(SourceFile, 'r') as source:
# print(content.readlines())
for loan in content:
# print(loan, end='')
if loan in source:
print('found loan')
with open(SourceFile) as dfile, open(loanFile) as ifile:
lines = "n".join(set(dfile.read().splitlines()) & set(ifile.read().splitlines()))
print(lines)
with open(NewFile, 'w') as ofile:
ofile.write(lines)
首先,将fileB
中的所有内容读入字典,其中键是标识符,值是整行
file_b_data = dict()
with open("fileB") as f_b:
for line in f_b:
line = line.strip() # Remove whitespace at start and end
if not line:
continue # If the line is blank, skip
row = line.split("~") # Split by ~
identifier = row[0] # First element is the identifier
file_b_data[identifier] = line # Set the value of the dictionary
接下来,读取fileA
中的行,并从字典
with open("fileA") as f_a, open("outfile", "w") as f_w:
for identifier in f_a:
identifier = identifier.strip()
if not identifier:
continue
if identifier in file_b_data: # Check that the identifier exists in previously read data
out_line = file_b_data[identifier] + "n" # Get the value from the dict
f_w.write(out_line) # Write it to output file
或者,您可以使用pandas
模块将所有fielA
和fileB
读取到数据框中,然后找到正确的行。
import pandas as pd
file_b_data = pd.read_csv("fileB.txt", sep="~", names=["identifier", "date", "path", "something"], index_col=0)
这给了我们这个数据帧:
identifier date path something
272991 20210129 \Serv1LOC7675309867530 16618272991.pdf 0
272992 20210129 \Serv1LOC7675309867530 16618272992.pdf 0
272993 20210129 \Serv1LOC7675309867530 16618272993.pdf 0
同样的fileA
:(我删除了272992来说明它实际上是有效的)
file_a_data = pd.read_csv("fileA.txt", names="identifier")
给我们identifier
0 272991
1 272993
然后,在file_b_data
中查找这些索引:
wanted_ids = file_a_data['identifiers']
wanted_rows = file_b_data.loc[wanted_ids, :]
wanted_rows.to_csv("out_file.txt", sep="~",header=None)
,它将写这个文件:(注意272992
行丢失了,因为它不在fileA
中)
272991~20210129~\Serv1LOC7675309867530 16618272991.pdf~0
272993~20210129~\Serv1LOC7675309867530 16618272993.pdf~0