Search code examples
pythonfiletextreadfilefwrite

Python Print to File Not Working


I am trying to execute this script:

text_file = open("/Users/test/Test/test.txt", "r")
f = open('/Users/test/TEST/test2.txt','w')
list1 = text_file.readlines()
for item in list1:
    number=0
    while number < 7:
        string=str(item)+str(number)
        number = number + 1
        f.write(string)

The file test.txt contains:

a
b
c
d

Expected output when I open test2:

a0
a1
a2
a3
a4
....(actual writing)
d6

Actual output:

a
0a
1a
2a
3a
4b
0b
1b
2b
3b
4c
0c
1c
2c
3c
4d0d1d2d3d4

Just WHAT is going on? Any help would be appreciated


Solution

  • You forgot to strip the '\n' from item. Use str.rstrip for that.

    for item in list1:
        for number in xrange(7):
            string = item.rstrip() + str(number)
            f.write(string + '\n')