在Python中,您可以使用`os`和`os.path`模块来查找文件。以下是一些示例代码,展示了如何使用这些模块进行文件查找:
1. 使用`os.walk()`遍历目录:
import osdef search_files(path, name):for root, dirs, files in os.walk(path):if name in files:return os.path.join(root, name)return Nonepath = input('请输入您要查找哪个盘中的文件(如:D:\\\)')name = input('请输入您要查找的文件名:')file_path = search_files(path, name)if file_path:print('找到文件:', file_path)else:print('查无此文件')
2. 查找特定文件名的文件:
import osfile_name = 'example.txt'dir_path = os.getcwd()for root, dirs, files in os.walk(dir_path):for file in files:if file == file_name:file_path = os.path.join(root, file)print('找到文件:', file_path)
3. 查找包含特定字符串的文件:
import ospath = 'Day1-homework'filename = '2020'result = []def find_files(files_path, files_list):files = os.listdir(files_path)for s in files:s_path = os.path.join(files_path, s)if os.path.isdir(s_path):find_files(s_path, files_list)elif os.path.isfile(s_path) and filename in s:result.append(s_path)find_files(path, result)for i in range(len(result)):print('[{}] {}'.format(i, result[i]))
4. 查找特定后缀的文件:
import osPATH = 'C:\\tmp\\test'SUFFIX = '.md'for root, dirs, files in os.walk(PATH):for file in files:if file.endswith(SUFFIX):print(file)
5. 在当前目录及其子目录下查找包含指定字符串的文件:
import ostestfiles = []testfilepaths = []L = len(os.path.abspath('.'))def search_file(path):for item in os.listdir(path):if os.path.isdir(os.path.join(path, item)):search_file(os.path.join(path, item))else:if 'test' in item:print(item, path[L:])search_file(os.path.abspath('.'))
以上代码展示了如何使用`os.walk()`函数遍历目录,以及如何使用`os.path.join()`、`os.path.endswith()`等方法来查找文件。您可以根据需要修改这些代码,以适应您的具体需求

