-2

I created a python program to provide a diff file. Wanted to know what the best way to send the results of the diff into a .csv would be

Here's my code,

import difflib

file1 = "swiss1.csv"
file2 = "swiss2.csv"

diff = difflib.ndiff(open(file1).readlines(),open(file2).readlines())

for line in diff:
    if line[0] in ["+", "-"]:
        print line

Rather than print to the terminal I would like to print it to a CSV file. Thoughts?

gboffi
  • 22,939
  • 8
  • 54
  • 85
  • 'write to file python' this is the google search term for your problem – Hossain Muctadir Mar 28 '16 at 19:06
  • Possible duplicate of [Correct way to write line to file in Python](http://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file-in-python) – Ectropy Mar 28 '16 at 19:11
  • @Ectropy that doesn't work. I'm trying to print the diff data from the program. I'm not trying to write data in f.write() – Stefan Petkovic Mar 28 '16 at 19:39
  • So heres my origional code, import difflib import csv file1 = "swiss1.csv" file2 = "swiss2.csv" diff = difflib.ndiff(open(file1).readlines(),open(file2).readlines()) for line in diff: if line[0] in ["+", "-"]: print line – Stefan Petkovic Mar 28 '16 at 19:42

1 Answers1

0
import difflib
import csv
file1 = "swiss1.csv"
file2 = "swiss2.csv"

diff = difflib.ndiff(open(file1).readlines(),open(file2).readlines())
f = open('changes.csv','w')
for line in diff:
    if line[0] in ["+", "-"]:
        f.write(line)
f.close()
gboffi
  • 22,939
  • 8
  • 54
  • 85