Python Forum

Full Version: get the number in the line in text file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I need your help (again)
I try to get the number who is stock in the line I need to get. this number can be up to three digits (like ###) and I need to get it and make a var with it, increment it by one, and replace the value in the line per the new value but keeping the other lines intact. my text file look like that.
14
23
3
7
58
1
7
41
41
327
my text file have 40 line (but I don't think that will impact the script)
I have already try this:
f = open("C:\data\data.txt")
    line=f.readlines(1)
    f.close()
    line=str(line)
    try:
        line=int(line)
    except ValueError:
        pass
    line+1
    print(line)
    open("C:\data\data.txt",'w').write(lines.join(line))
    break
but they write 0 whatever the file contain. and I try many other solution was never result except error message. I have search for answer for my problem in many forum, maybe I search in the wrong place. I am really grateful to you who answers us, is probably not easy and you do your possible each time to reply to everybody. thank you.
first, you are overwriting data.text each time you run, use a different file name for output
you can greatly simplify the code
def process_file(filename_in, filename_out):
    with open(filename_in) as fp, open(filename_out, 'w')  as fo:
        for line in fp:
            intval = int(line.strip())
            print(intval)
            fo.write('{}\n'.format(intval))

process_file('c:\data\data.txt', 'c:\data\newdata.txt')
thank for you reply