解析后写入文件

时间:2016-09-28 04:00:06

标签: python file-writing

我编写了一个小python代码,它将读取一个示例csv文件并将其第一列复制到temp csv文件。现在,当我尝试将该临时文件与另一个文本文件进行比较并尝试将结果写入另一个名为result file的文件时,该文件已创建但内容为空。

但是当我用大块测试它时,它工作正常

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

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

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

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

sample.csv

  

M11435TDS144,STB#1,路由器#1

     

M11543TH4292,STB#2,路由器#1

     

M11509TD9937,STB#3,路由器#1

     

M11543TH4258,STB#4,路由器#1

serialNumber.txt

  

G1A114042400571

     

M11543TH4258

     

M11251TH1230

     

M11435TDS144

     

M11543TH4292

     

M11509TD9937

2 个答案:

答案 0 :(得分:0)

您应先关闭输出文件(temp1.csv),然后才能从中读取数据。

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

data = open("temp1.csv", "w")
w = csv.writer(data)
for row in reader:
    my_row = []
    my_row.append(row[0])
    w.writerow(my_row)
data.close()  # <--- Should close it before reading it in the same program !!

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

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

答案 1 :(得分:0)

有关代码的要点

  • data文件句柄未关闭。写入data.close()temp1.csv
  • 在您的代码same = set(file1).intersection(file2)中,您直接将文件句柄file2传递给十字路口。它预计列表。这是确切的问题。它应该是same = set(file1.readlines()).intersection(file2.readlines())

工作代码:

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 = []
    if len(row) != 0:
      my_row.append(row[0])
      w.writerow(my_row)
#File should be closed
data.close()

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


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

temp1.csv的内容:

M11435TDS144
M11543TH4292
M11509TD9937
M11543TH4258

result.txt的内容:

M11543TH4258
M11543TH4292
M11435TDS144

您可以使用with打开文件 sample.csv temp1.csv ,如下所示。

import csv

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


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

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