0

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.

ImNotPsychotic
  • 47
  • 1
  • 10
  • 2
    You are opening your file in `read` mode. Use `w+` to read and write. – kaveh May 17 '19 at 01:14
  • use `with open("test.txt", "w+") as file:` instead. – Boris Verkhovskiy May 17 '19 at 01:15
  • opening the file in `w+` mode will [truncate it for you](https://stackoverflow.com/questions/1466000/python-open-built-in-function-difference-between-modes-a-a-w-w-and-r/30566011#30566011) – Boris Verkhovskiy May 17 '19 at 01:21
  • So when i do that, its given me a Permission Error ```Traceback (most recent call last): File "", line 2, in file = open("test.txt", "w+") PermissionError: [Errno 13] Permission denied: 'test.txt'``` – ImNotPsychotic May 17 '19 at 01:48
  • +Boris I Get a permission Denied error? Could it be because its open in CoolTerm? – ImNotPsychotic May 17 '19 at 01:54
  • Permission denied means you do not have the rights to write to that file. It may be owned by somebody else, or you might have removed the write permissions from the file yourself with `chmod` (or whatever the command is on your miserable commercial OS, as the case may be). This is a very basic question which is easily googlable, and no longer related to what you asked in the question. – tripleee May 17 '19 at 04:55

1 Answers1

-1

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()}')
xksa
  • 3
  • 2
Salman Arshad
  • 343
  • 6
  • 23