Python Forum

Full Version: How to add 1 in a text file ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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():
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')
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
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; }
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)
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))
just to mention that this will work with singe digits, i.e. it will not work with test 10 for example
Thanks it work.