You guys were super helpful with my last newbie question so I figured I would give it another shot. Right now, my Python 3 code takes data from a CSV file, stores the data as a list, creates permutations of that data, and exports it back out into a new csv file in a column format. Unfortunately, the format of the exported list is not the best for what I need it for. My question is: How do I remove the commas, brackets, and parenthesis from the exported list in python?
How it Looks Now:
('Hello', 'World', 'How')
('Hello', 'World', 'Are')
('Hello', 'How', 'World')
How I would like it to look:
Hello World How
Hello World Are
Hello How World
Here is the code I am using, does anyone have any advice or suggestions? I am trying to learn so any extra insight would be much appreciated!
import csv
import itertools
with open('/users/Desktop/pythondata.csv', 'r') as f:
reader = csv.reader(f)
J = []
for row in reader:
J.extend(row)
C = list(itertools.permutations(J, 3))
with open('THISISATEST.csv','w')as f:
writer=csv.writer(f,lineterminator='\n')
for val in C:
writer.writerow([val])`
P.S. -- Please forgive me if this is not formatted correctly, I am new to the board!
解决方案
Your question:
I recommend that you just use the join method to get the single string you are looking for. You could try:
with open('test.csv', 'w') as a_file:
for result in C:
result = ' '.join(result)
a_file.write(result + '\n')
Basically, the join method called on a the string ' ' (a single space) will take each item in its argument (a single result from your permutations) and add them together in a single string separated by whatever that first string was (the single space). This site gives a simple, illustrative example.
The join method is called with the syntax '[separator]'.join([list of items to join]), so if you just wanted to mash everything together into one string with no spaces, you could call it on an empty string: ''.join([my list]).
Since you do not need a comma-separated file (CSV), you can simplify things by just using the a_file.write method as shown. If you use the CSV writer in this code you will get commas between every letter.