Reputation: 43
Im writing the list deck into a file, however i need each item in each list to not have ' ' around it when written in.
deck = [['ad','ah','ac','as'],['2d','2h','2c','2s'],['3d','3h','3c','3s'],['4d','4h','4c','4s'],['5d','5h','5c','5s'],['6d','6h','6c','6s'],['7d','7h','7c','7s'],['8d','8h','8c','8s'],['9d','9h','9c','9s'],['td','th','tc','ts'],['jd','jh','jc','js'],['qd','qh','qc','qs'],['kd','kh','kc','ks']]
f = open('list.txt','w')
for i in deck:
a=str(i)[1:-1].strip("'")+"\n"
f.writelines(a)
f.close()
As seen in the code above ive tried to use .strip() but that isnt working as its only removing the first and last quotation. Would there be a way to get the text file to look like this:
ad, ah, ac, as
2d, 2h, 2c, 2s
3d, 3h, 3c, 3s
4d, 4h, 4c, 4s
etc...
Upvotes: 0
Views: 86
Reputation: 1271
What you try to perform is to write in csv fromat. Namely try something like this:
import csv
with open('list.txt','w') as f:
writer = csv.writer(f, quoting=csv.QUOTE_NONE)
writer.writerows(deck)
Upvotes: 1
Reputation: 24234
Use join
to join the different parts of each sublist with ', '
:
deck = [['ad','ah','ac','as'],['2d','2h','2c','2s'],['3d','3h','3c','3s'],['4d','4h','4c','4s'],['5d','5h','5c','5s'],['6d','6h','6c','6s'],['7d','7h','7c','7s'],['8d','8h','8c','8s'],['9d','9h','9c','9s'],['td','th','tc','ts'],['jd','jh','jc','js'],['qd','qh','qc','qs'],['kd','kh','kc','ks']]
with open('list.txt','w') as f:
for sublist in deck:
f.write(', '.join(sublist)+'\n')
Output (in list.txt
):
ad, ah, ac, as
2d, 2h, 2c, 2s
3d, 3h, 3c, 3s
...
Also, note that it is better to use with open...
to make sure that your file gets closed whatever happens.
Upvotes: 1
Reputation: 7852
You can work along the lines of this:
for each in deck:
for INDEX, EACH in enumerate(each):
if INDEX==0:
print(EACH,end='')
else:
print(','+EACH,end='')
print('\n')
Producing the output:
ad,ah,ac,as
2d,2h,2c,2s
3d,3h,3c,3s
4d,4h,4c,4s
...
Upvotes: 1
Reputation: 21565
Simply use .replace("'", "")
instead of .strip("'")
. Strip only removes the characters from the left and right side of the string and not in the middle, which is why you see the array being printed as ad', 'ah', 'ac', 'as
on each line:
deck = [['ad','ah','ac','as'],['2d','2h','2c','2s'],['3d','3h','3c','3s'],['4d','4h','4c','4s'],['5d','5h','5c','5s'],['6d','6h','6c','6s'],['7d','7h','7c','7s'],['8d','8h','8c','8s'],['9d','9h','9c','9s'],['td','th','tc','ts'],['jd','jh','jc','js'],['qd','qh','qc','qs'],['kd','kh','kc','ks']]
f = open('list.txt','w')
for i in deck:
a=str(i)[1:-1].replace("'", "")+"\n"
f.writelines(a)
f.close()
Upvotes: 1