0

My code is currently taking in a csv file and outputting to text file. The piece of code I have below and am having trouble with is from the csv I am searching for a keyword like issues and every row that has that word I want to output that to a text file. Currently, I have it printing to a JSON file but its all on one line like this "something,something1,something2,something3,something4,something5,something6,something7\r\n""something,something1,something2,something3,something4,something5,something6,something7\r\n"

But i want it to print out like this:

"something,something1,something2,something3,something4,something5,something6,something7" "something,something1,something2,something3,something4,something5,something6,something7"

Here is the code I have so far:

def search(self, filename):
        with open(filename, 'rb') as searchfile, open("weekly_test.txt", 'w') as text_file:
            for line in searchfile:
                if 'PBI 43125' in line:
                    #print (line)
                    json.dump(line, text_file, sort_keys=True, indent = 4)

So again I just need a little guidance on how to get my json file to be formatted the way I want.

Jongware
  • 22,200
  • 8
  • 54
  • 100
Turtle 23
  • 21
  • 4
  • 1
    Possible duplicate of [How can I open multiple files using "with open" in Python?](http://stackoverflow.com/questions/4617034/how-can-i-open-multiple-files-using-with-open-in-python) – dawg Feb 01 '16 at 15:45
  • that is not what I am trying to do. – Turtle 23 Feb 01 '16 at 18:50

1 Answers1

1

Just replace print line with print >>file, line

def search(self, filename):
    with open('test.csv', 'r') as searchfile, open('weekly_test.txt', 'w') as search_results_file:
        for line in searchfile:
            if 'issue' in line:
                print >>search_results_file, line

    # At this point, both the files will be closed automatically
Anmol Singh Jaggi
  • 8,376
  • 4
  • 36
  • 77