Pythonic way to modify all items in a list, and save list to .txt file
file, list, python
Solution
Instead of your last line, use:
f.write("\n".join(newList))
This will write the strings in newList, separated by newlines, to f. Note that if you don't actually need newList, you can combine your two loops and write the strings as you go:
the_list = ['a', 'b', 'c']
with open('myFile.txt', 'w') as f:
for num in range(4):
for letter in the_list:
f.write("%s%s\n" % (letter, num))
Problem
I have a list of strings. ``` theList = ['a', 'b', 'c'] ``` I want to add integers to the strings, resulting in an output like this: ``` newList = ['a0', 'b0', 'c0', 'a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3'] ``` I want to save this to a .txt file, in this format: ``` a0 b0 c0 a1 b1 c1 a2 b2 c2 a3 b3 c3 ``` The attempt: ``` theList = ['a', 'b', 'c'] newList = [] for num in range(4): stringNum = str(num) for letter in theList: newList.append(entry+stringNum) with open('myFile.txt', 'w') as f: print>>f, newList ``` Right now I can save to the file myFile.txt but the text in the file reads: ``` ['a0', 'b0', 'c0', 'a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3'] ``` Any tips on more pythonic ways to achieve my goal are very welcome,