Reputation: 4122
I have a string that I am trying to write to file where the data has the following format:
100.10 89.7 1,891.43 123.99
Which I want converting to the following format:
"100.10","89.7","1,891.43","123.99",
However using the following code (where filepath
is defined earlier in the code as a text file location and data2
is a string:
csv.register_dialect('sas', delimiter=',',quoting=csv.QUOTE_ALL)
with open(filepath, "w") as f:
writer = csv.writer(f, dialect='sas')
writer.writerow(data2)
I am getting this output:
"1","0","0",".",1,"0","8","9",".","7","1","8","9","1",".","4","3","1","2","3",".","9","9",
I want to use quotes to mask the presence of possible commas in the data, what am I doing wrong?
Upvotes: 0
Views: 69
Reputation: 394775
my_string = '100.10 89.7 1891.43 123.99'
string_list = my_string.split()
And string_list returns:
['100.10', '89.7', '1891.43', '123.99']
When you do:
csv.register_dialect('sas', delimiter=',',quoting=csv.QUOTE_ALL)
with open(filepath, "w") as f:
writer = csv.writer(f, dialect='sas')
writer.writerow(data2)
It's splitting data2 by character, so when you read it back in it's reading each character as a separate column. You probably want this:
csv.register_dialect('sas', delimiter=',',quoting=csv.QUOTE_ALL)
with open(filepath, "w") as f:
writer = csv.writer(f, dialect='sas')
writer.writerow(data2.split())
Edit
So I might suggest a different tack, forget about registering a dialect, for me that has always been problematic anyways.
string_list = ['100.10', '89.7', '1,891.43', '123.99']
with open(filepath, 'w') as f:
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
writer.writerow(string_list)
with open(filepath, 'r') as f:
print f.read()
For me printed:
"100.10","89.7","1,891.43","123.99"
And
with open(filepath, 'rU') as f:
reader = csv.reader(f, quoting=csv.QUOTE_ALL)
data = next(reader) # next(reader) gives us the iterable's first row.
data
returns:
['100.10', '89.7', '1,891.43', '123.99']
So when you write, do this:
with open(filepath, "w") as f:
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
writer.writerow(data2.split()) # *write here
You are probably intending to write a bunch of rows, so be sure to either loop through your rows that you want to write, or use writerows
instead of writerow
. See the examples in the documentation.
Upvotes: 2
Reputation: 121944
You are passing a string to writerow
, so it iterates over characters, putting a comma between each one. The minimal fix is:
writer.writerow(data2.split(" "))
Alternatively, it is probably more convenient to keep the data in a list rather than making a string in the first place!
Upvotes: 2