No matter what projects you’re working on, chances are that you’ll have to deal with files either on your computer or on a server. After all, files are the most common containers for storing related, usually organized information. However, I’ve found that many people, sometimes including myself, have to search some particular operations pertinent to file handling. Thus, in this article, I’d like to review the most ten useful techniques in Python.

1. Show Current Directory

When we want to know what our current work directory is, we can simply use the getcwd() function of the os module, as shown below.

>>> # To find out the current work directory
... import os
... print("Current Work Directory:", os.getcwd())
... 
Current Work Directory: /Users/ycui1/PycharmProjects/Medium_Python_Tutorials
>>> # Alternatively, we can use the pathlib
... from pathlib import Path
... print("Current Work Directory:", Path.cwd())
... 
Current Work Directory: /Users/ycui1/PycharmProjects/Medium_Python_Tutorials

The above code also shows you that we can use the pathlib module to get the current work directory. Please note that the pathlib module becomes the preferred way to handle file-related operations, and you’ll see more of its usages here in this article. However, if you’re working on an old version of Python (< 3.4), you may have to stick to the os module.

#python #artificial-intelligence #data-science

Top 10 File Handling Techniques in Python
6.70 GEEK