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?

Dani AI

Generated

The traceback "ValueError: invalid literal for int() with base 10: 'o\n'" means the counter file no longer contains a valid decimal string — it literally contains the character sequence "o\n" (letter o plus newline), so int(...) fails. That explains why adding the third block appears to "break" line 4: the write/overwrite code added by the third block (or a previous run of it) changed the file contents, so the next run fails immediately when reading and converting the file. was right to check the file exists; and pointed toward safer I/O and alternative persistence.

A quick diagnostic worth running first is to show exactly what was read (escaped): the repr() of the read string reveals stray characters, whitespace or non-digits. For example:

with open('/home/name/Desktop/text.txt', 'r') as f:
    data = f.read()
print(repr(data))

If the result is not a plain number (e.g. '0\n' or '42'), int() will raise the shown ValueError.

A small, robust pattern that avoids os.remove, uses open() (works in Python 2 and 3), converts before writing, and creates the file if missing:

path = '/home/name/Desktop/text.txt'
with open(path, 'a+') as f:
    f.seek(0)
    raw = f.read().strip()
    if raw == '':
        i = 0
    else:
        i = int(raw)   # will raise a clear ValueError if contents are bad
    i += 1
    f.seek(0)
    f.truncate()
    f.write(str(i) + '\n')

Notes: converting the integer to a string before write prevents type errors; opening in 'w' truncates so os.remove is unnecessary; avoid file() (Python 3 lacks it) and avoid bare except: blocks so real problems are not hidden.

If atomic updates or multi-process access matter, consider writing to a temporary file and using os.replace() or use a simple binary store (pickle/shelve) as suggested.

Recommended Answers

All 5 Replies

Make sure the file actually exists!

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.

@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)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.