Python Forum
How to add 1 in a text file ? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to add 1 in a text file ? (/thread-6052.html)



How to add 1 in a text file ? - jacklee26 - Nov-04-2017

Do anyone know how to add 1 to a text file.
For example :
Test.txt contain:
test 1
test 2
test 3

I wish to add 1 to the file and write to a new file NewTest.txt.
So the newtest.txt should output like it
test 2
test 3
test 4

with open('test.txt') as f:
new_file = open("newtest.txt", "w")
for item in f.readlines():


RE: How to add 1 in a text file ? - snippsat - Nov-04-2017

Use code tag BBcode help,use Ctrl+Shift+v when copy in to preserve indentation.
with open('data.txt') as f,open('new.txt', 'w') as f_out:
    lst = [i.strip() for i in f]
    lst.append('test 4')
    f_out.write('\n'.join(lst))
To append to existing file.
with open('data.txt', 'a') as f:
    f.write('test 4\n')



RE: How to add 1 in a text file ? - jacklee26 - Nov-04-2017

Actually, i want to change the integer to plus 1
test 1 +1
test 2 +1
test 3 +1
How do i change ? All the integer add 1

so the new file should look like
test 2
test 3
test 4


RE: How to add 1 in a text file ? - Larz60+ - Nov-05-2017

since test 1 is a string, you need something like:
mystr = 'test 1'
mystr = mystr[:-1] + str(int(mystr[-1:]) + 1)
print(mystr)
which will produce:
Output:
test 2
[align=initial !important]   [/align]
#s3gt_translate_tooltip_mini { display: none !important; }


RE: How to add 1 in a text file ? - jacklee26 - Nov-05-2017

is there any example with reading a file
How does this implement into a file
mystr = 'test 1'
mystr = mystr[:-1] + str(int(mystr[-1:]) + 1)
print(mystr)


RE: How to add 1 in a text file ? - Larz60+ - Nov-05-2017

it doesn't, but snippsat showed you how to do that.
with open('data.txt') as f,open('new.txt', 'w') as f_out:
    for line in f:
        line = line.strip()
        line = line[:-1] + str(int(line[-1:]) + 1)
        f_out.write('{}\n'.format(line))



RE: How to add 1 in a text file ? - buran - Nov-05-2017

just to mention that this will work with singe digits, i.e. it will not work with test 10 for example


RE: How to add 1 in a text file ? - jacklee26 - Nov-06-2017

Thanks it work.