简体   繁体   中英

How to compare two files data to check for a match then output to a new file in python 3.4

I am making a system that needs to search two .txt files for matching information (registration plates), if the system finds a match then it needs to output the lines from both files to a new file. The files: one contains data on speeding vehicles (regplate:speed data), the other contains vehicles registrations and owners details ( regplate:owners information). I have currently created a system that will find the owners information using an input and a line.startswith () command but I need the system to check through every plate in the speeding file and check if the same plate is in the owners information file, if it is then both pieces of data should be outputted to a new file. Is there a way I can do this with the .startswith()?. If not what other ways do you suggest. In both files every line starts with a different registration plate.

My current code:

    import re
with open("Speeding.txt", "r") as f:
    list1 = []
    for line in f:
        list1.append(line)
listnew = str(list1)
listnew.replace("\n", "")


new=open('SpeedersDetails.txt', 'a')

platecheck=input('Input plate: ')

with open('Plates.txt', 'r') as platefilereopen:
    for line in platefilereopen:
        if line.startswith(platecheck):
            new.write(line)
            new.write('\n')

new.close()
f.close()

My files: Ownersdetails , Speeding

You could go through one file and create a dictionary defaultdict(list) with registration plates as keys, and "speed data" appended to the list value. Then go through the other file and for each registration plate in the dictionary, append "owners information". Now you can run through the dictionary items and output each entry with a list of length two.

for reg_plate, info_list in reg_plate_dict.items():
    if len(info_list) == 2:
        speed_data, owner_info = value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM