Next →

Why Work with Files?

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.

Reading a File

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.

Writing to a File

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.

Using 'with' for Safety

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)

Why This Matters in Analytics

Reading from files lets you access raw datasets, and writing to files allows you to save cleaned or processed data.