Python can read files from your computer and write new ones using built-in commands
The most common way to work with files in Python is the open() function. It opens a file, lets you read what is inside or add new content, and then you close it. Python handles the actual connection to your hard drive — you just tell it the filename and what you want to do.
Every file operation follows the same pattern: open the file, do something with it, close the file. If you skip the closing step, Python may not save your changes or may lock the file so other programs cannot use it.
Key Takeaways
- The open() function takes two pieces of information: the filename and the mode, which tells Python whether you are reading, writing, or adding to the file.
- Reading a file uses mode "r", writing uses "w" (which erases the old content), and adding uses "a" (which keeps the old content and adds to the end).
- Always close your file when you are done using the close() method, or use a with statement that closes it automatically.
- Python reads files as text by default, but you can read them line by line, all at once, or one character at a time depending on what you need.
Opening a file and choosing the right mode
When you call open(), you give it the filename and a mode. The mode tells Python what you plan to do. Mode "r" means read — open the file but do not change it. Mode "w" means write — create a new file or erase an old one and start fresh. Mode "a" means append — add new content to the end of an existing file without erasing what is already there.
Here is what each looks like:
| Mode | What it does | Example |
|---|---|---|
| "r" | Opens a file to read. The file must already exist. | file = open("notes.txt", "r") |
| "w" | Opens a file to write. Creates a new file or erases the old one. | file = open("notes.txt", "w") |
| "a" | Opens a file to append. Adds to the end without erasing. | file = open("notes.txt", "a") |
If you try to read a file that does not exist, Python stops and shows an error. If you try to write to a file that does not exist, Python creates it. If you write to a file that already exists, the old content disappears — so be careful with mode "w".
Reading files: all at once, line by line, or character by character
Once a file is open in read mode, you have three main ways to pull the content out. The read() method reads the entire file as one long string. The readlines() method reads the file and splits it into a list where each line is one item. The readline() method reads one line at a time, which is useful for very large files where you do not want to load everything into memory at once.
If your file contains a list of names, one per line, readlines() is often the easiest choice because you get each name as a separate item you can loop through. If your file is huge — gigabytes of data — readline() lets you process one line, throw it away, and move to the next without storing the whole thing in memory.
Here is a concrete example. Say you have a file called shopping.txt with three lines: milk, eggs, bread.
file = open("shopping.txt", "r") all_content = file.read() file.close()
The variable all_content now holds the entire file as one string: "milk\neggs\nbread" (the \n represents a line break). If you use readlines() instead, you get a list: ["milk\n", "eggs\n", "bread"]. Each item is one line, and you can loop through them one at a time.
Writing and adding content to files
Writing uses the same open() function but with mode "w" or "a". Once the file is open, you call the write() method and give it the text you want to put in the file. Python does not add line breaks automatically — if you want each piece of text on its own line, you have to add \n yourself.
Mode "w" erases everything in the file first, so it is useful when you want to replace the entire contents. Mode "a" keeps what is already there and adds your new text to the end, which is what you want if you are building up a log or a list over time.
file = open("log.txt", "a") file.write("Task completed at 3pm\n") file.close()
This opens log.txt, adds a new line to the end, and closes it. If log.txt did not exist, Python creates it. If it did exist, the new line is added after everything else.
Using the with statement to close files automatically
Forgetting to call close() is a common mistake. Python offers a safer way: the with statement. It opens the file, lets you work with it, and closes it automatically when you are done — even if something goes wrong in the middle.
with open("notes.txt", "r") as file: content = file.read() print(content)
The as file part gives you a variable to work with. Inside the indented block, the file is open. As soon as the block ends, Python closes it automatically. This is the pattern most Python programmers use because it is safer and cleaner.
Handling errors when files do not exist or cannot be read
If you try to read a file that does not exist, Python raises a FileNotFoundError. If you do not handle this error, your program stops. You can catch the error using a try and except block so your program keeps running and does something sensible instead.
try: with open("missing.txt", "r") as file: content = file.read() except FileNotFoundError: print("That file does not exist")
The code inside the try block runs first. If a FileNotFoundError happens, Python skips the rest of the try block and runs the except block instead. This way your program does not crash — it prints a message and keeps going.
Other errors can happen too. If you do not have permission to read a file, you get a PermissionError. If the file is locked by another program, you might get an IOError. You can catch multiple errors by listing them, or catch any error with a bare except (though that is less precise).
Working with file paths and directories
When you write a filename like "notes.txt", Python looks for it in the current working directory — the folder your Python script is running from. If your file is in a different folder, you need to give the full path.
On Windows, paths use backslashes: "C:\Users\YourName\Documents\notes.txt". On Mac and Linux, paths use forward slashes: "/Users/YourName/Documents/notes.txt". Python on Windows accepts forward slashes too, which makes your code work on both systems.
If you are not sure where your script is running from, you can use the os module to find out. Add import os at the top of your script, then call os.getcwd() to see the current directory. You can also use os.path.join() to build paths in a way that works on any operating system.
import os folder = "/Users/YourName/Documents" filename = "notes.txt" full_path = os.path.join(folder, filename) with open(full_path, "r") as file: content = file.read()
Frequently Asked Questions
What is the difference between write and append mode?
Write mode ("w") erases the entire file and starts fresh. Append mode ("a") keeps everything that is already in the file and adds your new text to the end. Use write mode when you want to replace the whole file. Use append mode when you are adding to a log or building up a list over time.
Do I have to close the file every time?
Technically no, but you should. If you do not close a file, Python may not save your changes right away, and other programs may not be able to use the file. The safest way is to use a with statement, which closes the file automatically when the block ends.
Can I read and write to the same file at the same time?
Not with the basic modes. Mode "r" is read-only, and mode "w" or "a" are write-only. If you need to both read and write, use mode "r+" or "a+", but these are less common and require more careful handling to avoid losing data.
What happens if I write to a file that does not exist?
Python creates the file for you. This works with both write mode ("w") and append mode ("a"). If the folder does not exist, Python stops with an error — you have to create the folder first.
How do I read just the first few lines of a huge file?
Use readline() in a loop with a counter, or use the itertools.islice() function to grab a specific number of lines. This way you do not load the entire file into memory, which matters when the file is gigabytes in size.