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
andy
: 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 orNone
, 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?