Posted under » Python on 26 Mar 2026
pathlib makes file handling easy by allowing you to open, read and write files directly through Path objects no need for manual path strings or separate functions.
Example: This code reads overwrite "let us write this text" into output.txt. Followed by appending "let us write another line". Finally read content from README.txt
# old text will be overwritten
with (p / 'README.txt').open('w') as file:
file.write("let us write this text")
# appending to a file on another line using \n
with (p / 'README.txt').open('a') as file:
file.write("\nlet us write another line")
with (p / 'README.txt').open('r') as file:
content = file.read()
print(content)
let us write this text
let us write another line