3

EDIT: The solution was simply changing how I was opening the file (thanks Primusa), not how I was replacing the information.

I am attempting to overwrite parts of a file, but my code does not work. When it runs, it completely erases 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 corresponding to a file name without the file type.
  • store: a dictionary containing file name keys as string and integer values.
  • f: a file containing multiple lines of integer lists.
  • c: an integer variable used to determine the integer to be accessed.
  • x and y: variables with values set as the column and row (respectively) of the integer to be accessed in the file.
  • w: a variable stored as either a boolean or None, used to determine whether the accessed integer should increase or decrease, and by how much.
  • s: a currently unused integer variable used to truncate part of the file.

Example of use:

Say I have a file Foo.txt, which has the following information stored in it:

0,2,3,7

11,3,6,4

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

What should happen:

Foo.txt is modified and now contains:

0,2,3,7

11,3,8,4

What actually happens:

Foo.txt still exists, but now contains:

Which is to say it is empty.

What is wrong with my code? Am I handling the file incorrectly, the variable calculations, syntax, or something else entirely?

The Eye
  • 59
  • 12
  • Right there in [the docs](https://docs.python.org/3/library/functions.html#open) - `'w' for writing (truncating the file if it already exists),` – wwii Apr 17 '18 at 02:42
  • 1
    Possible duplicate of [How to search and replace text in a file using Python?](https://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file-using-python) – wwii Apr 17 '18 at 02:46
  • Sorry, this is NOT a duplicate, especially as it has a completely different solution. – The Eye Apr 17 '18 at 17:41

1 Answers1

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

Opening a file in mode "w+" truncates the file, which means it deletes everything inside of it. All of the operations you do after this statement are on an empty file.

What I would suggest would be opening the file in read mode:

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

Loading the file into memory, making your changes, and then opening the file in "w+" mode and putting the file back down.

Lets 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 this is a very basic example so it doesn't take into account the newlines.

Primusa
  • 13,136
  • 3
  • 33
  • 53