os
moduleThe os
module in Python provides functions that help in interacting with the underlying operating system.
truncate()
methodThe truncate()
method truncates the given file descriptor or the file path with respect to the given length in bytes.
truncate(path, length)
path
: This is the file path.length
: This is the max length in bytes after truncation.This function returns nothing.
import osf_path = "file.txt"f_contents = "hello-world\nhello-edpresso"with open(f_path, "w") as f:f.write(f_contents)print("Before truncation contents of the file: ")f_contents = open(f_path).read()print(f_contents)os.truncate(f_path, 10)print("--" * 5)f_contents = open(f_path).read()print("After truncation contents of the file: ")print(f_contents)
os
module.f_path
.f_contents
.f_contents
to the file f_path
.f_path
are read. These are then printed to the console before the truncation.f_path
to 10 bytes using the os.truncate()
method. This method modifies the original file.f_path
are re-read. We then print these to the console after the truncation.