Reputation: 21
I am outputting two columns of a CSV file to a text file and its printing everything on a single line in the text file. Like this:
Product Name Counter({'Descriptions': 1, 'Descriptions':3})
But I want it to print out like this:
Product Name Counter({'Descriptions': 1,
'Descriptions': 3})
Here is the code I have so far:
import csv
import sys
from collections import defaultdict
from collections import Counter
data = defaultdict(list)
class dictionary:
with open ('practice.csv', 'rb') as f:
reader = csv.reader(f)
next(reader, None)
for row in reader:
data[row[2]].append(row[3])
text_file = open("test.txt", "w")
data_count = Counter()
for key in data.keys():
sys.stdout = text_file
print key, Counter(data[key])
text_file.close()
How can I get my text file not to print out on one line? Not sure how to get this to work.
Upvotes: 2
Views: 206
Reputation: 1711
The Counter({'Descriptions': 1, 'Descriptions':3})
stuff is the output of the Counter's __str__()
function. When you use print Counter(stuff)
, then this is implicitely called for a new object generated by Counter(stuff)
. If I understand correctly, you want to reformat this output.
You could do it by storing the output of Counter(data[key])
in a variable and then modify that output by adding newlines at all positions of the ,
in the output:
a = str(Counter(data[key]))
print '\n'.join(a.split(','))
Which would be quite ugly ;-)
You could, however, design your ouptut yourself: The keys of the Counter are accessible via a.keys()
, so you could add a loop:
a = Counter(data[key])
print key, 'Counter({',
for counter_key in a.keys():
print counter_key + ': ' + a[counter_key] + ','
print '})'
which iterates over the content of the counter and outputs the key-value combination from your Counter line by line.
Edit: The second part of your code would then look like this:
text_file = open("test.txt", "w")
for key in data.keys():
text_file.writelines(key + ' Counter({')
counted = Counter(data[key])
for counter_key in counted.keys():
text_file.writelines(' ' + counter_key + ': ' + counted[counter_key] + '\n')
text_file.writelines('})\n')
text_file.close()
Note: It's possible to iterate over the key/value pairs in the counter using
for counter_key, counter_value in counted.items():
Upvotes: 1
Reputation: 61
You need to put a new line at the end of each line with \n
Also have you tried adding rows with data.writer ?
import csv
with open('practice.csv', 'wb') as f:
data = csv.writer(f, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
data.writerow(['Spam'] * 5 + ['Baked Beans'])
data.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
adapted from example here: https://docs.python.org/2/library/csv.html
Upvotes: 0