Reputation: 11
I'm new to coding and have tried working this out myself, to no avail! I'm imputing rows from a csv file and writing them to a text file. The rows have a lot of data but I only want certain fields. Ive just about got it to write the fields I want i.e Reference number 12345, Date: 20/5/17, Incident Type: text... etc
The problem is all the rows are bunched together with no lines between them. Ideally I would like two or three lines apart i.e
Reference number 12345, Date: 20/5/17, Incident Type: text...
Reference number 23117, Date: 22/5/17, Incident Type: text...
Reference number 23117, Date: 22/5/17, Incident Type: text...
Eventually I would like to be able to write only rows that contain particular keywords i.e by Incident Type or particular date. At the moment tho I would be happy if I could get newlines between the rows so that it was easy to read. I have tried just about everything. "\n" just seems to print in the text file rather than create a new line.
This is the code im using, its probably a bit crude but I have gotten this far by trial and error.
import csv
import os
with open("raw.csv", "r") as f:
r = csv.reader(f)
for row in r:
r = [row for row in r]
r = [row[4] + "---" + row[1] + "---" + row[6] for row in r]
with open("txtfile.txt", "w") as output:
output.write(str(r)+"\r\n")
print("Written successfully")
Upvotes: 0
Views: 1070
Reputation: 25829
You have to print a new line after each line, not after the whole string. Start with:
with open("raw.csv", "r") as f, open("txtfile.txt", "w") as output:
r = csv.reader(f)
for row in r:
output.write("{} --- {} --- {}\n".format(row[4], row[1], row[6]))
and take it from there. For additional formatting of your text file check the str.format()
.
Also, you might want to use a 'proper' line separator for your platform (which roughly means \n
for everything normal as above, and \r\n
for Windows) if you intend to read your text files in applications not designed in this century. You can get the current platform's preferred separator from the os
module: os.linesep
.
Upvotes: 1