简体   繁体   中英

How to compare a specific column of two csv files?

Let's say I have two csv files - fileone and filetwo - and both have columns [category, name, price, vendor]. In the vendor column, fileone has value "Georgia Malayv" and filetwo has value "Georgia". As you can see, fileone and filetwo both have "Georgia" as a value in the vendor column. I want the code to check column vendor, and I want a new csv file to print the values that are almost identical.

For example:

  • fileone has these values:

     ['France', 'Pizza', 12.55, 'Georgia Malayv'] 
  • filetwo has these values:

     ['Belgium', 'Steak', 15.99, 'Georgia'] 

If you look at the last values of both files, you see 'Georgia' is in both of them, but they are not equal to each other. How can I tell the computer that these lines are - according to me because both files have 'Georgia' - equal to each other and it can print the entire row of filetwo ?

Can this be done? If I did not explain myself clearly enough, I will be happy to edit my question or answer yours. Here is what I tried:

with open('product1.csv', 'r') as mp, open('product2.csv', 'r') as yb:
    fileone = mp.readlines()
    filetwo = yb.readlines()

with open('update.csv', 'w') as outFile:
    for mp_item in fileone:
        for yb_item in filetwo:
            # mp_item[3] is the vendor column
            if mp_item[3] == True:
                outFile.write(mp_item)

This code did not print anything in the new csv file.

This should do it:

with open ("update.csv", "w") as output_file:
    for mp_item in fileOne:
        for yb_item in fileTwo: 
            shortest = min (mp_item [3], yb_item [3])
            longest = max (mp_item [3], yb_item [3])
            if shortest in longest: 
                outFile.write (mp_item)

This determines which is longer, which is shorter, and checks if the shorter one is in the longer one.

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