简体   繁体   中英

file writing not working as expected

I have a python code where it will take the first column of a sample.csv file and copy it to temp1.csv file. Now I would like to compare this csv file with another serialNumber.txt file for any common rows. If any common rows found, It should write to a result file. My temp1.csv is being created properly but the problem is the result file which is being created is empty.

script.py

import csv
f = open("sample.csv", "r")
reader = csv.reader(f)

data = open("temp1.csv", "wb")
w = csv.writer(data)
for row in reader:
    my_row = []
    my_row.append(row[0])
    w.writerow(my_row)
data.close()

with open('temp1.csv', 'r') as file1:
    with open('serialNumber.txt', 'r') as file2:
        same = set(file1).intersection(file2)
        print same

with open('result.csv', 'w') as file_out:
    for line in same:
        file_out.write(line)
        print line

sample.csv

M11435TDS144,STB#1,Router#1 
M11543TH4292,STB#2,Router#1 
M11509TD9937,STB#3,Router#1
M11543TH4258,STB#4,Router#1

serialNumber.txt

G1A114042400571
M11543TH4258
M11251TH1230
M11435TDS144
M11543TH4292
M11509TD9937
with open('temp1.csv', 'r') as file1:
    list1 = file1.readlines()

set1 = set(list1)

with open('temp2.csv', 'r') as file2:
    list2 = file2.readlines()

set2 = set(list2)

now you can process the contents as sets

I want to note that your original code does not insert line breaks after each line so I am not sure if they would be present. If not you need to add those, otherwise you will have a mess

你可能想要这个

same = set(list(file1)).intersection(list(file2))

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