Want to code faster? OurPython Code Generator lets you create Python scripts with just a few clicks. Try it now!
In the software industry, most of the programs handle files in one way or another, such as creating files, renaming them, moving, listing, etc. As a programmer, you should definitely have this fundamental skill. As a result, in this tutorial, we will be usingos module in Python to make several operations on files and directories regardless of the operating system we're using.
Now, you need to know thatos module isn't only for handling files and directories, it has a ton of methods and tools for other operations, such as handling environment variables, command-line arguments, system process management, and even Linux extended attributes that are specific forLinux operating system.
Alright, let's get started, sinceos module is a built-in module, we don't have to install anything.
This may also interest you:How to Get the Size of Directories in Python.
In this tutorial, you will learn:
In order to get the current working directory, you need to useos.getcwd():
import os# print the current directoryprint("The current directory:", os.getcwd())os.getcwd() returns a Unicode string representing the current working directory, here is my output:
The current directory: C:\pythoncode-tutorials\python-standard-libraryTo make a folder/directory in any operating system, all you need to do is:
# make an empty directory (folder)os.mkdir("folder")Once you execute this, it'll immediately spawn a directory named"folder" in the current working directory.
If you run this again, it will raise aFileExistsError, that's because the folder already exists, a good way to solve this, is to runos.mkdir() only if the folder doesn't exist, we can easily do this:
# running mkdir again with the same name raises FileExistsError, run this instead:if not os.path.isdir("folder"): os.mkdir("folder")os.path.isdir() function returnsTrue if thepathname we passed refers to an existing directory.
It is fairly easy to change directories, let's change to the folder we just created:
# changing the current directory to 'folder'os.chdir("folder")Now let's print the working directory again:
# printing the current directory nowprint("The current directory changing the directory to folder:", os.getcwd())Output:
The current directory changing the directory to folder: C:\pythoncode-tutorials\python-standard-library\folderLet's say you want to create not only one folder, but you want to create many nested folders:
# go back a directoryos.chdir("..")# make several nested directoriesos.makedirs("nested1/nested2/nested3")This will create3 folders recursively as shown in the following image:
In order to create files in Python, you don't need any module, you can use the built-in functionopen() which takes the filename you want to create as the first parameter and the mode you want to open the file with as a second parameter:
# create a new text filetext_file = open("text.txt", "w")# write to this file some texttext_file.write("This is a text file")I used"w" as file opening mode which stands forwrite, you can also use"a" for appending to existing files or"r" for reading existing files. For more information about file opening modes, check thispage.
It's pretty easy to rename a file using theos module, let's rename the file we just created:
# rename text.txt to renamed-text.txtos.rename("text.txt", "renamed-text.txt")os.rename() function takes2 parameters, the name of file or directory you want to rename, and the destination name you want to rename to.
We can useos.replace() function to move files or directories:
# replace (move) this file to another directoryos.replace("renamed-text.txt", "folder/renamed-text.txt")Note that this will overwrite the destination, so if there is another pre-existing file in"folder" that got the same name"renamed-text.txt", but different content, it will overwrite it.
Related: How to Encrypt and Decrypt Files in Python.
# print all files and folders in the current directoryprint("All folders & files:", os.listdir())os.listdir() function returns a list containing the names of the files in the directory, we passed nothing as a parameter, so it'll return the files and directories of the current working directory, here is my output:
All folders & files: ['folder', 'handling-files', 'nested1', 'text.txt']Okay, but what if we want to know the content of these folders too? We gonna need to use theos.walk() function instead:
# print all files & folders recursivelyfor dirpath, dirnames, filenames in os.walk("."): # iterate over directories for dirname in dirnames: print("Directory:", os.path.join(dirpath, dirname)) # iterate over files for filename in filenames: print("File:", os.path.join(dirpath, filename))os.walk() is a directory tree generator, it will iterate over all the directory trees, I've passed"." as the top of this tree, which refers to the current working directory, here is the output:
Directory: .\folderDirectory: .\handling-filesDirectory: .\nested1File: .\text.txtFile: .\handling-files\listing_files.pyFile: .\handling-files\README.mdDirectory: .\nested1\nested2Directory: .\nested1\nested2\nested3I've also usedos.path.join() method to join the current path we're in, with the file/directory name.
Let's remove that file we created:
# delete that fileos.remove("folder/renamed-text.txt")os.remove() does what its name suggests, it removes a file (not a directory) given its pathname. Alternatively, you can useos.unlink() to do the exact same thing.
Usingos.rmdir() function will delete a given folder:
# remove the folderos.rmdir("folder")To delete directories recursively, we need to useos.removedirs() function instead:
# remove nested foldersos.removedirs("nested1/nested2/nested3")This will remove all these directories only if they're empty of course.
In order to delete non-empty directories (directories that has files, and subdirectories as well), we need to usermtree() method fromshutil:
# remote non-empty foldersshutil.rmtree("nested1")This method will recursively delete the entirenested1 directory tree, of course, you'll need the necessary privileges to do so, as it's quite dangerous if you're unconscious about what you're doing.
Related:How to Organize Files by Extension in Python
In order to get some information about a given file in your operating system, there is a cool functionos.stat() which performs astat system call on the given path:
open("text.txt", "w").write("This is a text file")# print some stats about the fileprint(os.stat("text.txt"))Here is the output:
os.stat_result(st_mode=33206, st_ino=14355223812608232, st_dev=1558443184, st_nlink=1, st_uid=0, st_gid=0, st_size=19, st_atime=1575967618, st_mtime=1575967618, st_ctime=1575966941)This returned a named tuple that got some metrics on it, we won't cover all these attributes, but some are interesting:
st_size: The size of the file in bytes.
st_atime: Time of most recent access expressed in seconds (timestamp).
st_mtime: Time of most recent modification.
st_ctime: In Windows, this is the time of the creation of the file, in Unix, this is the time of the most recent metadata change.
To get a specific attribute, you can do as follows:
# get the file size for exampleprint("File size:", os.stat("text.txt").st_size)Output:
File size: 19Checkthis page for further information about these attributes.
As you can see, it is very easy to handle files and directories in Python using this platform-independent module, in which you don't need to worry about any platform-specific handling, etc. You can also use some platform-specific functions, such asos.chown() oros.chmod() for Linux.
Of course, we didn't cover everything, please readPython's official documentation for further details.
Learn also: How to Download Files in Python.
Happy Coding ♥
Want to code smarter? OurPython Code Assistant is waiting to help you. Try it now!
View Full Code Explain The Code for MeGot a coding query or need some guidance before you comment? Check out thisPython Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!
