Python Files Input Output Functions

Programs often need to read data from a file or save results for later, and Python's built-in file handling functions make this straightforward, whether you're loading a dataset or writing out a report.

Opening a File

The open() function is used to open a file in a particular mode, such as read ("r"), write ("w"), or append ("a").

file = open("data.txt", "r")
content = file.read()
file.close()

Reading Files Line by Line

file = open("data.txt", "r")
for line in file:
    print(line.strip())
file.close()

Writing to a File

file = open("output.txt", "w")
file.write("Result: 42\n")
file.close()

Using the with Statement

The with statement opens a file and automatically closes it once you're done, even if an error occurs while working with it.

with open("data.txt", "r") as file:
    content = file.read()
print(content)
In data science workflows, file handling is used constantly to load raw datasets and to save processed results, logs, or trained model outputs, so using with is considered best practice.

Coming Up

With file handling covered, the next topic moves into one of Python's most-used data structures for storing collections of values: lists, and the operations you can perform on them.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course