Reputation: 2183
I'm trying to extract a list of dictionary values into a file with the following code:
import csv
def function(file, output, deli = ','):
dictionary = dict()
with open(file, 'r') as source, open(output, 'w') as outp:
data = csv.reader(source)
line0 = next(data)
i = 0
for element in line0:
dictionary[i] = element
i += 1
my_writer = csv.writer(outp)
for element in dictionary.values():
print(element)
my_writer.writerow(element)
if __name__ == '__main__':
from sys import argv
if len(argv) == 2:
function(argv[1])
elif len(argv) == 3:
function(argv[1], argv[2])
elif len(argv) == 4:
function(argv[1], argv[2], argv[3])
print("ok")
To run this code on the shell, I use the command: python function.py input output
However, trying on a csv file like: alpha, beta, gamma, delta
I get the following result:
a,l,p,h,a
,b,e,t,a
,g,a,m,m,a
,d,e,l,t,a
I tried to change the delimiter to ' ' and I got the same result with spaces instead of commas.
Am I missing something?
Upvotes: 1
Views: 2688
Reputation: 4755
The problem is in the lines
for element in dictionary.values():
print(element)
my_writer.writerow(element)
From the docs argument to writerow
should be a list of objects. In your case the argument is a string (which is iterable).
So what you are actually doing is my_writer.writerow("alpha")
which is written as a,l,p,h,a
.
You should simply do
my_writer.writerow(element.values())
Also, you are getting leading commas beacuse your CSV string is alpha, beta, gamma
. So when the split happens the elements are ['aplha',' beta',' gamma',]
. You could use strip()
to remove them
Upvotes: 2
Reputation: 13709
You are looping over the characters in the line instead of the actual elements
with open(file_, 'r') as source, open(output, 'w') as outp:
data = csv.reader(source, delimiter=deli)
#line0 = next(data)
i = 0
for element in data:
dictionary[i] = element
i += 1
also it's considered to be good practice to not override the built-ins in this case you are overriding file
, instead PEP 008 recommends that you add an underscore to the end of you variable name.
Upvotes: 0