In data analytics, you'll often read data from or write results to files — especially CSVs and text files. Python makes this easy using the open()
function.
To read the contents of a file:
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
The "r"
stands for read mode.
To write data to a file:
file = open("output.txt", "w")
file.write("This is a test.")
file.close()
The "w"
stands for write mode — it will overwrite the file if it already exists.
A better way to manage files is with a with
block, which automatically closes the file:
with open("data.txt", "r") as file:
content = file.read()
print(content)
Reading from files lets you access raw datasets, and writing to files allows you to save cleaned or processed data.