GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing thepythoncode.com — How to Handle Files in Python - The Python Code Struggling with multiple programming languages? No worries. Our Code Converter has got you covered. Give it a go! 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 using os module in Python to make several operations on files and directories regardless of the operating system we're using. Now, you need to know that os 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 for Linux operating system. Alright, let's get started, since os 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:
Printing the Current Working DirectoryIn order to get the current working directory, you need to use os.getcwd():
os.getcwd() returns a Unicode string representing the current working directory, here is my output:
Creating DirectoriesTo make a folder/directory in any operating system, all you need to do is:
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 a FileExistsError, that's because the folder already exists, a good way to solve this, is to run os.mkdir() only if the folder doesn't exist, we can easily do this:
os.path.isdir() function returns True if the pathname we passed refers to an existing directory. Changing DirectoriesIt is fairly easy to change directories, let's change to the folder we just created:
Now let's print the working directory again:
Output:
Creating Nested DirectoriesLet's say you want to create not only one folder, but you want to create many nested folders:
This will create 3 folders recursively as shown in the following image: Creating FilesIn order to create files in Python, you don't need any module, you can use the built-in function open() 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:
I used "w" as file opening mode which stands for write, you can also use "a" for appending to existing files or "r" for reading existing files. For more information about file opening modes, check this page. Renaming FilesIt's pretty easy to rename a file using the os module, let's rename the file we just created:
os.rename() function takes 2 parameters, the name of file or directory you want to rename, and the destination name you want to rename to. Moving FilesWe can use os.replace() function to move files or directories:
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. Listing Files and Directories
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:
Okay, but what if we want to know the content of these folders too? We gonna need to use the os.walk() function instead:
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:
I've also used os.path.join() method to join the current path we're in, with the file/directory name. Deleting FilesLet's remove that file we created:
os.remove() does what its name suggests, it removes a file (not a directory) given its pathname. Alternatively, you can use Deleting DirectoriesUsing os.rmdir() function will delete a given folder:
To delete directories recursively, we need to use os.removedirs() function instead:
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 use
This method will recursively delete the entire Related: How to Organize Files by Extension in Python Retrieving Information About FilesIn order to get some information about a given file in your operating system, there is a cool function os.stat() which performs a stat system call on the given path:
Here is the output:
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:
Output:
Check this page for further information about these attributes. ConclusionAs 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 as os.chown() or os.chmod() for Linux. Of course, we didn't cover everything, please read Python's official documentation for further details. Learn also: How to Download Files in Python. Happy Coding ♥ Let our Code Converter simplify your multi-language projects. It's like having a coding translator at your fingertips. Don't miss out!
Sharing is caring!
Read alsoLogging in PythonLearn how to use Python's built-in logging module to log your Python applications, changing default format, level, and learning in a concrete example, as well as using logging handlers. How to Use Regular Expressions in PythonLearn how to use Python's built-in re module to use several string matching techniques using functions like match, search, finditer and sub. How to Generate Random Data in PythonGenerating random integers, floating point numbers, strings and bytes using random, os and secrets built-in modules in Python. CommentsGot a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips! |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |