1. python使用OS库扫描指定路径下的文件
(网上找时有些凌乱,整理记录一下,方便需要时用)
a. 可实现扫描指定目录下的文件,或者匹配指定的前、后缀
- a. 如果要扫描指定目录下的文件,包括子目录,直接调用:ScanFile("/export/home/test/");
- b. 如果要扫描指定目录下的特定后缀的文件(比如py文件),包括子目录,调用:ScanFile("/export/home/test/", postfix=".py");
- c. 如果要扫描指定目录下的特定前缀的文件(比如IMGxxx.jpg),包括子目录,调用:ScanFile("/export/home/test/", prefix=“IMG”)。
注意:路径及匹配均大小写敏感
需要包含库
import os
函数实现:
def ScanFile(directory, prefix=None, postfix=None):
file_list = []
for root, sub_dirs, files in os.walk(directory):
for special_file in files:
# 如果指定前缀或者后缀
if postfix or prefix:
# 同时指定前缀和后缀
if postfix and prefix:
if special_file.endswith(postfix) and special_file.startswith(prefix):
file_list.append(os.path.join(root, special_file))
continue
# 只指定后缀
elif postfix:
if special_file.endswith(postfix):
file_list.append(os.path.join(root, special_file))
continue
# 只指定前缀
elif prefix:
if special_file.startswith(prefix):
file_list.append(os.path.join(root, special_file))
continue
# 前缀后缀均未指定
else:
file_list.append(os.path.join(root, special_file))
continue
# print(file_list) # 打印出扫描到的文件路径
return file_list
2. 修改python工程路径到指定目录:
# os.chdir(r'G:\MyProgram\python365\TestFfmpeg\ffmpeg\dll\\') # 绝对路径
os.chdir(r'.\ffmpeg\dll\\') # 相对路径