


Python3. Example of traversing a folder to extract specific file names
The following is an example of Python3 traversing a folder to extract a specific file name. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together
When processing files in batches, it is often necessary to first traverse a certain path to extract file names under specific conditions. This article writes a violent traversal but very concise method. It is really very concise but very violent.
The example goal is: Obtain the contents of the folder whose name ends with "_BAD" under the folder where remote sensing data is stored. Because there are many levels under this file (year/month/product type/), there are many target folders and they exist at the last level, so it is very annoying to check manually.
The code is as follows (after summarizing the knowledge points and code):
# -*- coding: utf-8 -*- """ 遍历某路径下所有文件夹,获得特定文件夹下所有文件 很暴力,真的遍历了所有的文件夹 20180124 @author: 墨大宝 """ import os TARGETPATH = r'F:\MODIS_DATA' records = [] for currentDir, _, includedFiles in os.walk(TARGETPATH): if not currentDir.endswith('_BAD'): continue else: records.append(currentDir) # 将以“_BAD”结尾的文件夹名加入records records.extend(includedFiles) # 将该文件夹内的文件名列表扩展到records # 将records写入.txt txtFile = open(os.path.join(TARGETPATH, '02_04_BAD.txt'), 'w') txtFile.write(os.linesep.join(records)) txtFile.close() # 将排序后的records写入.txt with open(os.path.join(TARGETPATH, '02_04_BAD_SORTED.txt'), 'w') as txtFile: txtFile.write('\n'.join(sorted(records)))
os.walk () Return Directory tree generator. Each time a tuple in the format of (dirpath, dirnames, filenames) is generated, the elements are the current path, the folder list under the current path, and the file name list under the current path.
List's .append(), .extend() and .sort() methods are all modified in place, but the sorted() function is not.
When writing a list to a .txt file, you need to convert the list to str. Directly using the str() function to force the conversion will be ugly. Using newlines to connect each element of the list will look much better.
os.path represents the system newline character, which is "\r\n" under Windows and "\n" in other systems. However, no matter whether you use os.path or "\n" to connect the list elements, and finally open it with Windows Notepad, the line breaks will be the same. However, if you open it with vs code, os.path will break one more line, which means it will look like one line between lines. What exactly is here? What I mentioned is that it may be related to Python's write mechanism, so I won't delve into it for the time being (leaving a hole).
Regarding file reading and writing, most information recommends the with as form, which is indeed more concise.
PS:
The reason why os.walk() is violent is that it really traverses all the files in the given path according to the directory tree. Folders and files, it will be slower if the file size is large and the file names you are looking for are few (in fact, I don’t think it is much slower). If you use os.listdir() to write a recursive function, the execution efficiency may be higher, but os.walk () The logic is simple and easy to write, feel free to do whatever you want, I did it!
Related recommendations:
Python example of deleting a non-empty folder
Python copies files to the specified directory
Python's method of obtaining the program execution file path
The above is the detailed content of Python3. Example of traversing a folder to extract specific file names. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



By default, Windows 11 does not display folder sizes in File Explorer, however, you can make certain changes in Explorer settings to make them visible. In this guide, we will discuss some of the easiest ways to display folder sizes so that you can effectively manage disk space on your PC. How to check the size of a folder on Windows 11? 1. Use the folder's Properties window to open a Windows Explorer window by pressing +. WindowsE Go to the folder whose size you want to check, right-click on it and select "Properties" from the context menu. In the folder properties window, go to the "General" tab and find the "Size" section to find out how much space the folder takes up. 2. Enable "

The win11 system has updated a lot of new wallpapers for everyone, so many users are curious about which folder the win11 wallpapers are in and want to open them to see the wallpapers inside. Therefore, we have brought a tutorial so that you can enter and view the wallpapers. . Which folder is the win11 wallpaper in: 1. The system comes with wallpaper: 1. First enter my computer, and then open the path: C:\Windows\Web\Wallpaper. 2. Then enter the windows folder and you can see the wallpapers that come with the system. 2. User-saved wallpapers: 1. Wallpapers installed by users will be saved in: C:\Users (user)\xx (current user name)\AppData\Local\Microso

In this article, we will show you how to automatically copy files to another folder on Windows 11/10. Creating backups is necessary to avoid data loss. Data loss can occur due to many reasons such as hard drive corruption, malware attack, etc. You can back up your data manually by using copy and paste method or using third-party tools. Did you know you can automatically back up data on your Windows computer? We'll show you how to do this in this article. How to have files automatically copied to another folder on Windows 11/10 How to use Task Scheduler to automatically copy files and folders to another destination folder on Windows 11/10? This article will provide you with detailed guidance. please

Recently, many friends feel that the theme of Win10 does not meet their own aesthetics and want to change the theme. After downloading it online, they find that the folder cannot be found. Then the editor will show you how to find the folder of the Win10 theme. Which folder is the win10 theme in? 1. The default storage path location of Win10 system wallpapers: 1. Microsoft saves these pictures in the path C:\Windows\Web\Wallpaper. Under it are the default saves of pictures with three different themes. Location, 2, flowers and lines and colors theme pictures are also saved in the folder with the same name! The naming principle is imgXXX. We only need to follow this principle to change the name of the related image we want to set and paste the image into

When you find that one or more items in your sync folder do not match the error message in Outlook, it may be because you updated or canceled meeting items. In this case, you will see an error message saying that your local version of the data conflicts with the remote copy. This situation usually happens in Outlook desktop application. One or more items in the folder you synced do not match. To resolve the conflict, open the projects and try the operation again. Fix One or more items in synced folders do not match Outlook error In Outlook desktop version, you may encounter issues when local calendar items conflict with the server copy. Fortunately, though, there are some simple ways to help

After updating to the latest win11 system, most friends don't know how to encrypt their folders to protect privacy, so we have brought you a method. Let's take a look at how to set a password for a win11 computer folder. How to set a password for a win11 computer folder: 1. First find the folder you want to encrypt. 2. Then right-click the folder and select "Properties". 3. Click "Advanced" under Properties. 4. Check "Encrypt content to protect data" in the menu and click OK. 5. Finally, return to the properties of the folder and click "OK" in the pop-up window.

Many users change wallpapers when using their computers. I believe many users are also asking which folder the win11 wallpapers are in? The wallpapers that come with the system are in Wallpaper under the C drive, and the wallpapers saved by users are in the Themes folder of the C drive. Let this site carefully introduce the win11 default wallpaper path sharing for users. Share win11 default wallpaper path 1. The system comes with wallpaper: 1. First enter my computer, and then open the path: C: Windows Web Wallpaper. 2. User-saved wallpapers: 1. Wallpapers installed by users will be saved in: C: Users (user) xx (current user name) AppDataLocalM

The Windows folder contains the Windows operating system and is an important folder in a Windows computer. By default, Windows is installed on the C drive. Therefore, C is the default directory for Windows folders. Every Windows computer has a Windows folder. However, some users reported that two Windows folders were found in the C drive. In this article, we will explain what you can do if you encounter such a situation. Two Windows folders in C drive It is rare to have two Windows folders in C drive. However, if you encounter such a situation, you can use the following suggestions: Run an anti-malware scan to try to find the correct
