Python gets the current path and lists all the files under the current path
Description of the problem
Because you need to read multiple files, but if you enter the name and read them one by one, it will be abnormally inefficient, as a programmer, how can you endure this torture????
So, now the question is how to get the current path and get all the files in the specified directory and then process each file individually?
prescription
First get the current path, using the following code:
import os path = ()# Get current path print(path)
Output:
'/home'
Then get the name of the file in the current path
all_files = [f for f in (path )]# Output all filenames under the root path into a list # Processing of individual documents print(all_files)
Output:
[ ‘tmp’,'user1']
You can get a list of all the files and folders in the specified directory from above.
Takeaway:
python supports a lot of os commands, you need to familiarize yourself with them in the process of using them.
python recursively get all file paths in a directory (folder)
Example 1: Fundamentals 1
# Get the names of files and folders in a directory import os dir_path = './' file_list = (dir_path) print(file_list)
Output results:
[‘request_data’, ‘’, ‘testcase’, ‘venv’]
Note: There are files and folders
Example 2: Get only the path of files and folders in the current directory.
def get_filepath(dir_path): file_list = (dir_path) for file in file_list: file_path = (dir_path, file) # Splice into paths print(file_path) if __name__ == '__main__': get_filepath('./')
Output results:
./request_data
./
./testcase
./venv
Example 3: Examples at work
# Recursively get the paths of all files in a directory (folder) import os def get_filepath(dir_path, list_name): """Recursively get the paths of all files in a directory (under a folder)""" for file in (dir_path): # Get file (folder) name file_path = (dir_path, file) # Complete file (folder) names to paths if (file_path): # If folder, recursive get_filepath(file_path, list_name) else: list_name.append(file_path) # Save path return list_name res = get_filepath('./') for i in res: print(i)
Output results:
…/log\bsp2_1_20210708.log
…/log\bsp2_1_20210709.log
…/log\bsp2_1_20210710.log
…/log\bsp2_1_20210711.log
summarize
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.