Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

In simplest terms, when i try to run a short amount of code to delete the contents of a file and then rewrite stuff to that file, it pulls that error. I'm trying to get a temperature reading from a com port using the filewrite from CoolTerm, perhaps it's the fact that the file is being used by CoolTerm as well, so I can't edit it, but I'm unsure.

I've tried multiple ways to delete the file information e.g the file.close(), and others, but none seem to work.

while True:
    file = open("test.txt","r")
    file.truncate()
    x = file.read()
    x = x.split("\n")
    print(x[0])
    print(x[1])
    time.sleep(3)

I expect the console to output the contents of file but it doesn't. Something that gives me a similar result of what i want would be the Console just outputting the last two entries of the file, rather than having to delete all of it than rewriting it.

So when i do that, its given me a Permission Error Traceback (most recent call last): File "<pyshell#40>", line 2, in <module> file = open("test.txt", "w+") PermissionError: [Errno 13] Permission denied: 'test.txt' – ImNotPsychotic May 17, 2019 at 1:48

Modified to r+ mode is ok, I have tested.

with open('./install_cmd', 'r+') as f:
    print(f'truncate ago:{f.read()}')
    f.truncate(0)
    print(f'truncate after:{f.read()}')
                When i had done that i got this Error "ValueError: must have exactly one of create/read/write/append mode"
– ImNotPsychotic
                May 17, 2019 at 1:21