Python – Overwriting part of a file results in an empty string Python 3

Overwriting part of a file results in an empty string Python 3… here is a solution to the problem.

Overwriting part of a file results in an empty string Python 3

EDIT: The solution just changes the way I open the file (thanks Primusa), not the way I replace the information.

I tried to overwrite part of the file, but my code doesn’t work. When it runs, it completely deletes everything in the file, leaving nothing behind.

Here is my code :

for fname in store:
    with open(fname + ".txt", "w+") as f:
        for line in f:
            c = store[fname]
            x = (c-1)%len(line.split(","))
            y = m.floor((c-1)/len(line.split(",")))

for n in range(y):
                f.readline()

ldata = line.strip("\n").split(",")
            for i in range(len(ldata)):
                ldata[i] = int(ldata[i])

if w == None:
                ldata[x] += 1
            elif w == True:
                ldata[x] += 2
            elif w == False:
                ldata[x] -= 1

#s = line.find("\n") - 1
            #f.truncate(s)
            f.write(str(ldata) + "\n")

Key:

  • fname: A string variable for file names without file types.
  • store: A dictionary containing filename keys as string and integer values.
  • f: File containing a list of integer rows with multiple lines.
  • c: An integer variable that determines the integer to access.
  • x and y: Variables whose values are set to the columns and rows (respectively) of the integer to be accessed in the file.
  • w: A variable stored as a bool value or none that determines whether the integer accessed should be increased or decreased, and by how much.
  • s: An integer variable that is not currently in use to truncate a portion of the file.

Usage example:

Let’s say I have a file Foo.txt which stores the following information:

0,2,3,7

11,3,6,4

I

want to increase the “6” value by 2, so I set w to True and add “Foo": 7 to the store when I run the code, because “6” is the 7th number in the file (regardless of the list length).

What should happen:

Foo.txt has been modified to now include:

0,2,3,7

11,3,8,4

What actually happened:

Foo.txt still exists, but now contains:

That is, it is empty.

What’s wrong with my code? Did I mishandle files, variable calculations, syntax, or something completely different?

Solution

with open(fname + ".txt", "w+") as f:

Opening a file in “

w+” mode truncates the file, which means it deletes everything in it. All actions that you perform after this statement are for an empty file.

I recommend opening the file in read mode :

with open(fname + ".txt", "r") as f:

Load the file

into memory, make changes, and then open the file in “w+” mode and put the file back.

Let’s do this on the foo example:

with open("foo.txt", 'r') as f: #open in read mode
    a = f.read().split(',') #breaking it apart so i can locate the 6th number easier
    a[6] = str(int(a[6]) + 2) #make my modifications
    a = ','.join(a) #convert it back to string
with open("foo.txt", 'w+') as f: #open in write and delete everything
    f.write(a) #write my modified version of the file

Note that this is a very basic example, so it doesn’t take line breaks into account.

Related Problems and Solutions