-1

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

Geno
  • 3
  • 3

2 Answers2

1

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()
shaktimaan
  • 1,769
  • 13
  • 14
  • Thank you so much shaktimaan! Tried your advice but I just end up with an empty txt. file!? Don’t know what I’m doing wrong though.. Any thoughts? – Geno Apr 14 '15 at 12:30
  • Oh I am really sorry I forgot to close the files. just put outfile.close() in end. – shaktimaan Apr 14 '15 at 12:43
  • Any ways a piece of advice to avoid such errors in future, in file handling always use with statement. ** with open(file, 'r') as f: lines = f.readlines();,** this take cares of closing file automatically – shaktimaan Apr 14 '15 at 12:48
  • No worries! Now everything thing is working perfectly, thanks again!! – Geno Apr 14 '15 at 12:50
  • All right, I'll indeed use that advice in the future, thx! :) – Geno Apr 14 '15 at 12:51
0

For Python 3,

filename = input("Enter filename: ")
with open(filename, 'r+') as file:
    lines = file.readlines()
    file.seek(0)
    for line in lines:
        value = int(line)
        file.write(str(value + 1))
    file.truncate()
SKO
  • 32
  • 5