Opening Files in Python
Python allows you to read files stored on your system using simple built-in functions. Files can be opened from the same directory as your Python script or from any other location using a full file path.
Example File Structure
Assume a text file named
sample.txt
exists in the same directory as your Python program.
sample.txt
Reading a File Using open()
To access the contents of a file, Python provides the
open()
function. This function returns a file object that supports several methods
for reading data.
Example: Read the Entire File
The
read() method
loads the complete content of the file into memory.
Opening Files from Another Location
If the file is stored outside the current directory, you must provide the full file path.
Example: Read a File Using Absolute Path
Using the with Statement (Best Practice)
The
with keyword
simplifies file handling by automatically closing the file after use.
Example: Reading with with
-
No need to manually call
close() - Cleaner and safer code
Closing Files Manually
If you do not use the
with
statement, it is important to close the file explicitly.
Example: Closing a File
Reading Part of a File
The
read() method
can also limit the number of characters returned.
Example: Read First 8 Characters
Reading Files Line by Line
Read a Single Line
Read Multiple Lines
Loop Through All Lines
You can iterate directly over the file object to read each line one at a time.
- Efficient for large files
- Memory-friendly approach
