简体   繁体   English

文件写入未按预期工作

[英]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. 我有一个python代码,它将使用sample.csv文件的第一列并将其复制到temp1.csv文件。 Now I would like to compare this csv file with another serialNumber.txt file for any common rows. 现在,我想将此csv文件与另一个serialNumber.txt文件进行任何常见行比较。 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. 我的temp1.csv正在正确创建,但是问题是正在创建的结果文件为空。

script.py 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 sample.csv

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

serialNumber.txt 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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