0

First of all this is my Code:

c = open('Tasks//Task_Counter.txt', 'r+')
okay = c.read().splitlines()

which_task = int(okay[0])
this_task = which_task + 1 

which_port = int(okay[1])
this_port = which_port + 1

c.truncate(0)

c.write(str(this_task))
c.write("\n")
c.write(str(this_port))

In the Task_Counter.txt file are basically just these two lines written down:

10
9259

Now I wanna replace them with:

11
9260

But somehow this is the result:

        11
9260

As you can see there is just free Space and I dont know why there is this free Space. Can someone help me with this?

2 Answers2

1

.truncate() doesn't change the file cursor position. So you have to use .seek(0) to write at the begin. And don't forget to close your file. The best way is to use the context manager (with).

with open('foo.txt', 'r+') as c:
    okay = c.read().splitlines()

    which_task = int(okay[0])
    this_task = which_task + 1

    which_port = int(okay[1])
    this_port = which_port + 1

    c.truncate(0)
    c.seek(0)
    
    c.write(str(this_task))
    c.write("\n")
    c.write(str(this_port))
Sven Eberth
  • 3,057
  • 12
  • 24
  • 29
0

The reason is file is not empty after truncate(0) is explained by Garbage in file after truncate(0) in Python.

So a better way is the following:

def update(filenm):
    # Get values  this_task and this_port
    with open(filenm, 'r') as f:    # open for read
        this_task = int(next(f))
        this_port = int(next(f))
        
    # Store incremented values
    with open(filenm, 'w') as f:    # open for write (places stream at beginning of file)
        f.write(f'{this_task + 1}\n')
        f.write(f'{this_port + 1}\n')

# Test (attempt 100 times)
for _ in range(100):
    update('Task_Counter.txt.txt')

Data in file after 100 iterations

111
2160
DarrylG
  • 16,732
  • 2
  • 17
  • 23