Handling files is an entry-level and fundamental skill for any programmer. They're very commonly used to store application data, user configurations, videos, images, etc. There are a countless number of use-cases for files in software applications, so you'd be smart to make yourself deeply familiar with the tasks of manipulating files. These tasks could include (among others) creating, deleting, and moving files.
In this article, we'll cover the process of working with files using the Python programming language. The built-in methods it offers makes it very easy to handle files using a relatively small amount of code. As with anything in programming, there are many ways to achieve the same goal when it comes to files, but in this article we'll stick with the basics and show the most common ways to perform these actions.
Creating Files in Python
File Opening Modes
There are modes in which you can open a file in Python. The mode you choose depends on how you plan to use the file, or what kind of data you'll be reading (writing) from (to) the file. This mode is specified when opening a file using the built-in
open() method, explained in further detail in the next section.
Let's take a look at some of the possible combinations of file modes:
w: Opens a file for writing and creates a new file if it doesn't yet exist. In the case that the file does exist, it overwrites it.
w+: Opens a file for writing but also for reading and creating it if it doesn't exist. If a file already exists, it overwrites it.
r: Opens a file for reading only.
rb: Opens a file for reading in Binary format.
wb: Opens a file for writing in Binary format.
wb+: Opens a file for writing and reading in Binary format.
a: Opens a file for appending at the end of the file.
+: In general, this character is used along side
aand means both writing and reading.
If no file mode is specified, then
r will be assumed by default.
When choosing a mode, take in to careful consideration what your use-case is and what all the file will be used for for the duration that it is open.
As with just about anything in Python, performing many file-related tasks is very simple. For example, creating a file in Python can be done in a single line of code:
myFile = open("new.txt", "w+")
In the example above we have opened a file, "new.txt" for reading and writing. In our case, since the file does not already exist, it is automatically created.
open() method accepts many arguments, although the majority of the time you'll only use these two:
- filename – Required field to specify the name of the file we wish to open/create. In our example, "new.txt"
- mode – Optional argument to specify the file opening mode, in our example "w+"
You can omit the second argument, in which case it will be assumed by Python as
The other arguments not listed here allow you to configure buffering, encodings, newline handling, etc. For more info on these arguments, check out the official Python documentation on the
When you open a file you always need to make sure that you also close it. This can be done using the file object's
close() method, or opening it using the
with keyword that Python provides, which closes it automatically when out of scope. After closing the file, it won't be available for reading or writing within your code anymore, unless you open it back up.
Keeping your files open will use up system resources, slow down your program, and in some cases prevent the file from being used by other code. Python's garbage collection does it's best to automatically close files when they're not being used anymore, but you shouldn't rely on it.
If a file is already closed, calling
close() on it again won't affect it at all:
myFile.close() myFile.close() # Doesn't affect the file
Moving Files in Python
To move a file in Python, we will need to import the
shutil modules that provide us the ability to copy, move, and remove files in Python. Both of these modules provide methods to do so, although in many cases the
shutil module has more convenient methods.
import os import shutil # Move a file by renaming it's path os.rename('/Users/billy/d1/xfile.txt', '/Users/billy/d2/xfile.txt') # Move a file from the directory d1 to d2 shutil.move('/Users/billy/d1/xfile.txt', '/Users/billy/d2/xfile.txt')
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Keep in mind that the destination directory needs to exist in order for this example to work. Once you've set up the directories "d1" and "d2" (or just changed the example to fit your directory structure), run the code. Now check out the "d2" directory and you should see the xfile.txt if now present in that directory.
Pretty simple, right?
Deleting Files in Python
As you probably guessed, it's pretty easy to remove a file in Python using the
remove() method from the
In our example below, we'll delete the "xfile.txt". All we need to do is call the
remove() method with the path of the file we want to delete:
import os # Delete xfile.txt os.remove('/Users/billy/d2/xfile.txt')
Now check out the "d2" directory again and the file xfile.txt will now be done. Simple as that!
In this article, we showed very simple examples of how to create, move, and delete files in Python using the built-in functions such as
os.remove(). In addition, we presented a simple introduction and explanation of Python file modes.