Python allows you to work with the file system, which includes both files and directories. Using the built-in system functions, you can access, manipulate, open, read, write, append, and close files.

Opening a File

To open a file, use the open function. The first parameter is the path to the file, with the second being the mode.

Here is the list of modes:

  • r: Opens a file for reading.
  • a: Opens a file for appending.
  • w: Opens a file for writing.
  • x: Creates a new file.

Let's use the first one to open a file:

PYTHON
file = open("file.txt", "r")

That's pretty much it. As long as the file exists, you have successfully opened a file in Python!

Reading a File

Now that you've opened a file, let's read from it. Use the read() function on the file:

PYTHON
file = open("file.txt", "r") print(file.read())

Assuming the file contained this text:

HTML
Hello! Welcome to sabe.io! Have fun!

That is exactly what you would see when you try to print it out. If you want to limit the number of characters returned back, give the length as the parameter, like so:

PYTHON
file = open("file.txt", "r") print(file.read(6))
BASH
Hello!

Read File Line by Line

Maybe instead of getting the entire file, you want to read it line by line. Thankfully, there is already a built-in function for this. The readline() function reads a file line by line each time. If you use it twice, the second time will return the second line.

PYTHON
file = open("file.txt", "r") print(file.readline()) print(file.readline())
HTML
Hello! Welcome to sabe.io!

Alternatively, you can just loop over the lines, like so:

PYTHON
file = open("file.txt", "r") for line in file: print(line)
HTML
Hello! Welcome to sabe.io! Have fun!

Closing a File

Closing a file is important because it is sometimes needed to ensure any changes to a file are propagated in the file system.

This is how to close a file once you're finished with it:

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

Our file is now closed!

Appending to Existing File

You can append text to an existing file pretty easily. Simply switch the mode when you open and use the write() function:

PYTHON
file = open("file.txt", "a") file.write("Coding is fun!") file.close() file = open("file.txt", "r") print(file.read())
HTML
Hello! Welcome to sabe.io! Have fun! Coding is fun!

Overwriting an Existing File

The only difference between appending and overwriting an existing file is the mode. Here is how you overwrite a file entirely:

PYTHON
file = open("file.txt", "w") file.write("Coding is fun!") file.close() file = open("file.txt", "r") print(file.read())
HTML
Coding is fun!

Creating new Empty Files

You can create a brand new file without any content in it by changing the mode to x:

PYTHON
file = open("file.txt", "x") file.close()

A new blank file has been created!

Renaming a File

To rename a file using Python, we must import the os module, then use its rename() function.

Here's how that looks:

PYTHON
import os os.rename("old_name.txt", "new_name.txt")

Pretty simple!

Deleting a File

Deleting a file also requires the use of the os module.

Here's how you do it:

PYTHON
import os os.remove("file.txt")

Check if a File Exists

To avoid an error with trying to remove a file that does not exist, you should check if the file exists before trying to remove it.

This is how you do it:

PYTHON
import os path = "file.txt" if os.path.exists(path): os.remove(path) else: print("This path does not exist: " + path)

Resources

Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.