In the course of learning Python, we will find that there are some modules and codes that are frequently mentioned and used by studying the office Automation section. This is especially true of OS, Shutil, Glob, etc.

Today’s content I will be divided into two parts to take you to repeat the Python office automation module, code implementation of high-frequency operations, easy to learn and flexible use in their own scripts!

01. The OS module is related

First, walk through the folder

The premise of batch operation is to traverse the folder, which can be easily traversed using the OS module. Os. walk generates three parameters after traversing:

  1. Current folder path
  2. Include folder names [in list form]
  3. Include file names [in list form]

The code is as follows, you can modify according to their own path

import os for dirpath, dirnames, filenames in os.walk(r'C:\\Program Files (x86)'): Print (f' open folder {dirPath}') # current folder path if dirnames: print(dirnames) # if filenames: Print (filenames) print('-' * 10)Copy the code

Os.walk can be used when you need to obtain all qualified files in all levels of folders in a given path and perform corresponding batch operations

2. Whether the destination path is a file

Sometimes we need to determine whether there are files in a directory can also use the OS module.

Given a destination path, one line of code can determine whether it is a file or folder path

import os

path = 'xxx'
print(os.path.isfile(path))
Copy the code

3. Obtain the file name in the path

Os.path. basename 'can get the last filename directly from the absolute path, or if you use the traditional string cutting method. 'path.split('\\')[-1] import OS path =' XXX 'print(os.path.basename)Copy the code

Create a folder

The code for creating folders is very common, because new files tend to want a new folder to store them in, as follows:

import os

dirpath = 'xxx'
os.mkdir(dirpath)
Copy the code

However, if the folder you want to create already exists, running os.mkdir() will abort the code with an error. To avoid this, determine whether a folder exists before creating it.

The code used is os.path.exists, which is created only if the path does not exist (that is, if os.path.exists returns False) :

import os

dirpath = 'xxx'
if not os.path.exists(dirpath):
    os.mkdir(dirpath)
Copy the code

Obtain the desktop path

To obtain the Desktop path, run os.path.join(os.path. expandUser (“~”), ‘Desktop’) to obtain the absolute Desktop path.

The advantage of this is that the data can be kept on the desktop and code can be called to process the data from different computers. If you fixed the desktop path to a string on one computer, you would have to change the desktop path on a different computer. The code is as follows:

import os

desktop_path = os.path.join(os.path.expanduser("~"), 'Desktop')
print(desktop_path)
Copy the code

Of course it would be more convenient to wrap the above code into a function called GetDesktopPath() whenever needed

import os

def GetDesktopPath():
    return os.path.join(os.path.expanduser("~"), 'Desktop')
Copy the code

Rename files/folders

The os.rename() method is required, and the following code example shows how to rename a file and a folder, respectively

Import OS os.rename('practice.txt', 'practice_rename ') # rename file os.rename(' folder 1', 'folder 2') # rename folderCopy the code

Batch file – 1

In addition to the previous os.walk, there are other OS module methods to obtain all or qualified files in a specified path (other than the need to traverse all levels of folders). You can also use the following two codes. The first method is os.scandir(), which is used as follows:

import os

path = 'xxx'
for file in os.scandir(path): 
    print(file.name, file.path)
Copy the code

Batch file – 2

The second method uses os.listdir(), which is simpler than os.scandir() and calls the output name instead of the path:

import os 

path = 'xxx'
for file in os.listdir(path):
    print(file)
Copy the code

02. Shutil module is related

Move files/folders

Shutil is also a module that is often used in office automation scenarios, where I move files/folders around.

The shutil.move method is required, and the following code example demonstrates moving files and folders, respectively:

Import shutil shutil.move(r'.practice.txt ', r'.practice.txt ') shutil shutil.move(r'.practice.txt ', r'.practice.txt '/new.txt')Copy the code

Notice the difference between the last two lines above? The first line moves the target file to the target folder, and the second line renames the target file while moving it to the target folder

That is, if we need to move one or more files to a new folder and rename the files, we don’t need to rename the file with os.rename and move it to the specified folder with shutil.move, but we can use shutil.move in one step

03 The GLOB module is related

X. Batch file – 3

Finally, the Glob module, which is a must for office automation, can also be used for batch files.

The most important function of glob is to search for files (absolute paths) that match conditions at the same level or sub-level, which is ideal for writing batch code.

Sometimes we need to do the same for a large number of files, and after we write an operation for one file, we just need to add a few lines of code, and we can batch the entire file. The general code framework is as follows:

import glob
    
for file in glob.glob('**/*', recursive=True): 
    print(file)
Copy the code

Glob. Glob () is a very important method that takes the absolute path of a file under a given path and accepts “wildcard” searches, greatly increasing flexibility. * denotes any character length, **/* denotes any level under a given path, recursive allows traversal.


These are the ten common Python automation operations I’ve compiled for you. Most of them are generic. You can save this article and copy and paste it whenever you need to do something about it.

In addition, I hope you can think more about which functions/code fragments you can use when writing your own code and reading others’ code, so that you can make progress faster!