Table of Contents
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:
PYTHONfile = 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:
PYTHONfile = open("file.txt", "r")
print(file.read())
Assuming the file contained this text:
HTMLHello!
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:
PYTHONfile = open("file.txt", "r")
print(file.read(6))
BASHHello!
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.
PYTHONfile = open("file.txt", "r")
print(file.readline())
print(file.readline())
HTMLHello!
Welcome to sabe.io!
Alternatively, you can just loop over the lines, like so:
PYTHONfile = open("file.txt", "r")
for line in file:
print(line)
HTMLHello!
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:
PYTHONfile = 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:
PYTHONfile = open("file.txt", "a")
file.write("Coding is fun!")
file.close()
file = open("file.txt", "r")
print(file.read())
HTMLHello!
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:
PYTHONfile = open("file.txt", "w")
file.write("Coding is fun!")
file.close()
file = open("file.txt", "r")
print(file.read())
HTMLCoding is fun!
Creating new Empty Files
You can create a brand new file without any content in it by changing the mode to x
:
PYTHONfile = 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:
PYTHONimport 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:
PYTHONimport 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:
PYTHONimport os
path = "file.txt"
if os.path.exists(path):
os.remove(path)
else:
print("This path does not exist: " + path)
Resources
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Getting Started with Moon.js