Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to modify all items in a list, and save list to .txt file

Tags:

python

file

list

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,

like image 428
Marchy Avatar asked Apr 16 '12 17:04

Marchy


2 Answers

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))
like image 57
Ned Batchelder Avatar answered Nov 15 '22 00:11

Ned Batchelder


If you want to compress your code a little bit you can do:

>>> n = 4
>>> the_list = ['a', 'b', 'c']
>>> new_list = [x+str(y) for x in the_list for y in range(n)]
>>> with open('myFile.txt', 'w') as f:
...     f.write("\n".join(new_list))
like image 36
luke14free Avatar answered Nov 14 '22 23:11

luke14free