Q:

PYTHON - Read and overwrite file and add each value by one

I’m trying to program a simple code in python that will overwrite my existing file and also add one to every value or line in my file. 
For example my “num.txt” file:

5 ---> 6
7 ---> 8
9 ---> 10
11 ---> 12
13 ---> 14

file = raw_input("Enter filename: ")
infile = open(file,'r')
for line in infile:

    value = int(line)
    infile.write(str(value + 1))
    infile.truncate()

infile.close()

Error message:
infile.write(str(value + 1))
IOError: File not open for writing

I really appreciate your help
Thx
Geno

A:

Your file is not open for writing, this line
infile = open(file,'r')

means that open the file for reading.
If you want to open the file for writing, you can use 'w' (write) or 'r+' (read and write) use this instead:
infile = open(file,'r+')

for more you can read (http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python) --> Mode Section.
If you use 'r+' the code should be something like
infile = open(file, 'r+')
for line in infile:
    val = int(line)
    infile.write(str(val + 1) + '\n')
    infile.truncate()
infile.close()

But I suppose this wont serve the purpose which you want to do, this will just append the values to the end. If you want to write these new values to file, use this instead:
infile = open(file, 'r')
lines = infile.readlines() #this gives a list of all lines
infile.close()
outfile = open(file, 'w') #erases previous contents
for line in lines:
   outfile.write(str(int(line) + 1) + '\n') #if you are sure file have int's only 
outfile.close()

