The basic way to read a file in Python

To read a file in Python, use the open() function with the filename and the mode "r" (for read). The simplest approach is to read the entire file at once using the read() method, which returns all the content as a single string.

Here is the actual code:

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

The close() method at the end tells Python you are finished with the file. This frees up the memory Python was using to hold the file open. If you forget to close the file, Python will eventually close it for you, but closing it yourself is the safer habit.

Key Takeaways

  • Use open("filename", "r") to open a file for reading, then call read() to get all the content as one string.
  • Always call file.close() when you are done, or use a with statement to close the file automatically.
  • Read one line at a time with readline(), or loop through all lines with readlines() or a for loop.
  • If the file does not exist or cannot be opened, Python will raise a FileNotFoundError — wrap your code in a try/except block to handle this gracefully.
  • The with statement is the modern, cleaner way to read files because it closes them automatically even if something goes wrong.

Reading one line at a time with readline()

If your file is very large or you only need the first few lines, reading the entire file into memory at once is wasteful. Use readline() to read one line each time you call it.

file = open("myfile.txt", "r") line1 = file.readline() line2 = file.readline() print(line1) print(line2) file.close()

Each call to readline() returns the next line in the file, including the newline character at the end (the invisible character that marks where one line ends and the next begins). If you reach the end of the file, readline() returns an empty string.

Looping through all lines with a for loop

The cleanest way to read every line in a file is to loop through the file object directly. Python treats an open file like a list of lines, so you can use a for loop.

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

This approach reads one line at a time as the loop runs, so it uses very little memory even for huge files. Each line variable holds one line from the file, including the newline character at the end.

If you want to remove the newline character, use the strip() method, which removes whitespace from both ends of a string:

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

Using the with statement to close files automatically

The with statement is the modern way to read files because it closes the file automatically when you are done, even if an error occurs. You do not have to remember to call close().

with open("myfile.txt", "r") as file: content = file.read() print(content)

The file closes automatically when the code inside the with block finishes running. This is safer because if something goes wrong inside the block, the file still gets closed. For this reason, with is the recommended approach for any new code you write.

You can also use with and a for loop together:

with open("myfile.txt", "r") as file: for line in file: print(line.strip())

Handling errors when a file does not exist

If you try to open a file that does not exist, Python raises a FileNotFoundError. To handle this gracefully, wrap your code in a try/except block.

try: with open("myfile.txt", "r") as file: content = file.read() print(content) except FileNotFoundError: print("The file does not exist.")

The code inside the try block runs first. If a FileNotFoundError occurs, Python skips the rest of the try block and runs the code inside the except block instead. This way your program does not crash — it prints a message and continues running.

You can also catch other errors, like permission problems:

try: with open("myfile.txt", "r") as file: content = file.read() except FileNotFoundError: print("The file does not exist.") except PermissionError: print("You do not have permission to read this file.")

Reading specific lines or sections of a file

Sometimes you only need certain lines from a file. Use readlines() to get all lines as a list, then access them by their position (called an index).

with open("myfile.txt", "r") as file: lines = file.readlines() print(lines[0]) print(lines[5])

In Python, counting starts at 0, so lines[0] is the first line and lines[5] is the sixth line. You can also use slicing to get a range of lines:

with open("myfile.txt", "r") as file: lines = file.readlines() first_ten = lines[0:10] print(first_ten)

The slice [0:10] means "from position 0 up to but not including position 10", so you get lines 1 through 10. Be aware that readlines() loads the entire file into memory, so for very large files, looping with a for loop is more efficient.

Frequently Asked Questions

What is the difference between read(), readline(), and readlines()?

read() returns the entire file as one string. readline() returns one line each time you call it. readlines() returns all lines as a list of strings. Use read() for small files you want all at once, readline() when you need one line at a time, and readlines() when you want to access lines by position.

Do I have to close a file after reading it?

Technically Python will close it eventually, but you should close it yourself or use a with statement. Closing frees up memory and prevents problems if your program tries to delete or move the file later. The with statement closes automatically, so it is the safest choice.

What happens if I try to read a file that is currently open in another program?

On most systems, you can read a file that another program has open. However, if another program is actively writing to the file, you might read incomplete or corrupted data. For this reason, it is best to read files that are not currently being modified.

How do I read a file from a different folder?

Use the full path to the file. On Windows, use backslashes or forward slashes: open("C:/Users/YourName/Documents/myfile.txt", "r"). On Mac or Linux, use forward slashes: open("/home/username/myfile.txt", "r"). You can also use relative paths like open("../folder/myfile.txt", "r") to go up one folder.

Can I read a file and store each line in a list without using readlines()?

Yes. Use a for loop with a list and the append() method: lines = [], then for line in file: lines.append(line.strip()). This gives you more control than readlines() and lets you clean up each line as you add it.