I'm very new to all of this, here's the code.

f="/home/name/Desktop/text.txt"
fil = open (f,"r")
data = fil.read()
i=int(data)
fil.close()

import os
os.remove(f)

i=i+1
inp=file(f,'w')
inp.write(i)
inp.close()

I'm pretty much trying to make the value in the text file increase by one each time the script is run. I realize that there must be much better ways to do it, but I'm just playing around :p.

It works the way it's supposed to until I add the third "pharagraph". But the problem isn't in the new code but in the old one.
This is the "output" I get from Idle when I run it:

  Traceback (most recent call last):
  File "/home/name/Desktop/script.pyw", line 6, in <module>
    i=int(data)
ValueError: invalid literal for int() with base 10: 'o\n'

But before I add the third part there is no problem with the first part. Why is this?

line 12 should not work, as parameter of write must be string, you do not need remove the file, just overwrite it. I would not use variable named inp for file opened for writing. It is slightly confusing to use file instead of open.

Edited 4 Years Ago by pyTony

@pyTony
But why would line 12 being wrong make idle say that line 4 is? Without 12 4 worked...
How do I overwrite the file then?

well i could say first it is better to import module in the start of the code and make sure the data in the file could be converted to int such as whitespaces
and data to write to a file must be a string..

#the best way
import os,sys
f="test.txt"
try:
    file=open(f,"r")
    i=int(file.read())
    file.close()
    os.remove(f)
except :#excepting errors such as IOError if the file not exist
    print "make sure the file exists!!"
    sys.exit()
i=i+1
try:
    file2=open(f,"a")#creating a new file with extra "1" char
    file2.write(i)
    file2.close()
except:#excepting all errors such as IOError
    print "writing to the file failed"
    sys.exit()

My version

# file contents counter
try:
    import cPickle as pickle
except:
    import pickle

import os

pickle_file = 'counter.pickle'
try:
    with open(pickle_file,'rb') as previous:
        counter = pickle.load(previous)
except IOError:
    counter = 1
except EOFError:
    print('Removing empty file')
    os.remove(pickle_file)
    counter = 1
except Exception as e:
    print('Other error: %s' % e)
    raise SystemExit(e)
else:
    counter += 1

try:
    with open(pickle_file, 'wb') as outf:
        pickle.dump(counter, outf, protocol=2)
except IOError as e:
    print('Failure in saving the file:\n%s' % e)
    raise SystemExit(e)

print('%i saved to file' % counter)
This article has been dead for over six months. Start a new discussion instead.