Reputation: 25
I am trying to output a combination from my_list 1 & 2
import itertools
import csv
my_list1=["+Red"]
my_list2=["+Lip +Stick","+Magic"]
# Please note: Space is kept intentionally in "+Lip +Stick" above
combinations=itertools.product(my_list1,my_list2)
with open('Txt_of_Keywords.txt','w') as f1:
writer=csv.writer(f1,lineterminator='\n',)
for c in combinations:
writer.writerow(c)
Output without delimiter:
+Red,+Lip +Stick
+Red,+Magic
I want to replace comma with space in the above output.
I tried adding space using delimiter as below:
writer=csv.writer(f1,delimiter=' ',lineterminator='\n',)
Output with delimiter:
+Red "+Lip +Stick"
+Red +Magic
Above output incorrectly writes quotation marks. This is because "+Lip +Stick" has space in between while defining my_list2. Sadly, i want that space there.
Please help me to replace comma with space (as highlighted above in bold).
Upvotes: 1
Views: 4242
Reputation: 140168
you're trying to lure csv
module into not quoting/escaping the space. Setting quoting
to csv.QUOTENONE
and/or csv.quotechar
to "empty" doesn't work, raising exceptions like:
quotechar must be set if quoting enabled
or
need to escape, but no escapechar set
csv
has checks to ensure that it cannot happen, for reversibility reasons.
So the best way would be to split each value and flatten the list of the tokens obtained with this generator comprehension fed to itertools.chain.from_iterable
:
writer.writerow(list(itertools.chain.from_iterable(x.split() for x in c)))
full example:
my_list1=["+Red"]
my_list2=["+Lip +Stick","+Magic"]
# Please note: Space is kept intentionally in "+Lip +Stick" above
combinations=itertools.product(my_list1,my_list2)
with open('Txt_of_Keywords.txt','w') as f1:
writer=csv.writer(f1,lineterminator='\n',delimiter=" ")
for c in combinations:
writer.writerow(list(itertools.chain.from_iterable(x.split() for x in c)))
now I'm getting:
+Red +Lip +Stick
+Red +Magic
You could also write your list without the csv
module at this point, since the main point of csv
is to easily escape chars that could interact with the delimiter and handle multi-line (see Martjin new answer for that).
Upvotes: 1
Reputation: 1121486
Why are the quotes 'incorrect'? You wrote a value containing a space, the writer uses quotes to make sure that space is not seen as a delimiter.
If you don't want to have quoting, you may as well just write your values directly to the file. If you use the print()
function, you'll get newlines and spaces for free:
with open('Txt_of_Keywords.txt','w') as f1:
for c in combinations:
print(*c, file=f1)
You can't tell the csv.writer()
object to ignore delimiters in values; your choices are between quoting, using an escape character, or if you disabled both, an error being raised. Your other option is to split your columns on the delimiter, but that's just more work just to make the csv
module work, where you don't really need to use that module at all.
Upvotes: 3