Clearing, rewriting and deleting files
Clearing a file
Opening a file with "w" empties it. So to clear a file, open it with "w" and write nothing. But a with block can't be empty: Python requires at least one statement in every indented block. For a block that should do nothing, Python has the statement pass, which does exactly nothing:
old line 1
old line 2with open("log.txt", "w") as file:
pass
with open("log.txt") as file:
contents = file.read()
print(len(contents))
0You have seen pass before: the starter code of a function task has pass as the function's body, so that the program runs before the real body is written.
Changing lines in the middle
"a" can only add to the end, and "w" starts from an empty file. To change or remove something in the middle of a file, a program reads the whole file into a list, changes the list, and writes the whole list back with "w":
wash the car
buy stamps
call the banktasks = []
with open("tasks.txt") as file:
for line in file:
tasks.append(line.strip())
tasks.remove("buy stamps")
tasks.append("water the plants")
with open("tasks.txt", "w") as file:
for task in tasks:
file.write(task + "\n")
with open("tasks.txt") as file:
print(file.read())
wash the car
call the bank
water the plantsThe order matters: read first, then write. Opening the file with "w" empties it at once, so a program that opens it for writing before reading it has nothing left to read.
Deleting a file
To delete a file completely, a program asks the operating system. Python's functions for that are in the os module, which a program takes into use with the line import os at its start (a later module tells more about modules). os.remove(name) deletes a file, and os.path.exists(name) tells whether a file exists:
import os
with open("draft.txt", "w") as file:
file.write("Just a draft\n")
print(os.path.exists("draft.txt"))
os.remove("draft.txt")
print(os.path.exists("draft.txt"))
True
FalseA deleted file doesn't go to a recycle bin: it's gone. Deleting a file that doesn't exist stops the program with a FileNotFoundError.