Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the ten Python office automation operations?

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

What are the ten Python office automation operations? in view of this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

1. Related to OS module

1. Traverse the folder

The premise of batch operation is to traverse the folder. You can easily traverse the folder using the os module. Three parameters are generated after os.walk traversal:

"the current folder path contains the folder name [list] contains the file name [list]"

The code is as follows. You can modify it according to your own path.

Import os for dirpath, dirnames, filenames in os.walk (ritual C:\\ Program Files (x86)'): print (f' Open folder {dirpath}') # current folder path if dirnames: print (dirnames) # contains folder name [list form] if filenames: print (filenames) # contains file name [list form] print ('-'* 10)

Os.walk can be used when the requirement at hand clearly acquires all qualified files under all levels of folders in a given path, and performs the corresponding batch operation.

two。 Whether the destination path is a file

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

Given a target path path, you can tell whether it is a file or a folder path by one line of code.

Import os path = 'xxx' print (os.path.isfile (path)) 3. Get the file name in the path

Os.path.basename can get the final file name directly from the absolute path, of course, if you use the traditional string cutting method, that is, path.split ('\) [- 1]

Import os path = 'xxx' print (os.path.basename) 4. Create a folder

The code to create a folder is not often used, because often the new files generated want to be stored in a new folder, as follows:

Import os dirpath = 'xxx' os.mkdir (dirpath)

However, if you want to create a folder that already exists, running os.mkdir () will terminate the code by reporting an error. To avoid this, you can determine whether the folder exists before you create it.

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

Import os dirpath = 'xxx' if not os.path.exists (dirpath): os.mkdir (dirpath) 5. Get Desktop path

Getting the desktop path is also a very common operation, and you can use os.path.join (os.path.expanduser ("~"), 'Desktop') to get the absolute path of the desktop.

The advantage of this is that you can put the data on the desktop and call code to process the data on different computers. If the desktop path is fixed in a string on one computer, the desktop path must be modified on another computer. The code is as follows:

Import os desktop_path = os.path.join (os.path.expanduser ("~"), 'Desktop') print (desktop_path)

Of course, it is more convenient to package the above code as a function GetDesktopPath () to call it when needed.

Import os def GetDesktopPath (): return os.path.join (os.path.expanduser ("~"), 'Desktop') 6. Rename files / folders

You need to use the os.rename () method. The following code example shows how to rename files and folders, respectively.

Import os os.rename ('practice.txt',' practice_rename.txt') # rename file os.rename ('folder 1', 'folder 2') # rename folder 7. Batch file-1

In addition to the previous os.walk, there are other methods under the os module that can obtain all or qualified files of the specified path (not required to traverse folders at all levels). You can also use the following two codes. The first method used is os.scandir (), using the following:

Import os path = 'xxx' for file in os.scandir (path): print (file.name, file.path) 8. Batch file-2

The last output of the above code is the name and absolute path of each content under the given path. The second method uses os.listdir (), which is simpler than os.scandir (), and can directly call the output name instead of the path:

Import os path = 'xxx' for file in os.listdir (path): print (fil2, shutil module related 9. Move files / folders

Shutil is also a module that often appears in office automation scenarios, and I often move files / folders.

The shutil.move method is required, and the following code example shows how to move files and folders, respectively:

Import shutil shutil.move (ringing.\ practice.txt', rushing.\ folder 1max') shutil.move (ringing.\ practice.txt', ringing.\ folder 1According to new.txt')

Notice the difference between the last two lines of code above? The first line moves the target file to the target folder, while the second line can rename the target file while moving it to the target folder.

That is, if we need to move a file or some files to a new folder and rename the file, we don't need to use os.rename to name the file first and then use shutil.move to move it to the specified folder. Instead, we can use shutil.move to move it in one step.

Third, glob module related 10. Batch file-3

Finally, I would like to introduce the glob module, which is also a module that must be mastered in office automation, and can also be used for batch processing files.

The most important function of glob is to search and get qualified files (absolute paths) at the same level or sub-level, which is very suitable for writing batch code.

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

Import glob for file in glob.glob ('* / *', recursive=True): print (file)

Glob.glob () is a very important method, which can get the absolute path of a file under a given path and accept a "wildcard" search, which greatly broadens the degree of flexibility. * represents any character length, the use of * * / * refers to any layer under a given path, and the recursive parameter allows traversal search.

The answers to the questions about the ten Python office automation operations are shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report