列出文件夹中的所有文件和文件夹
def open_folder(folder_path):
# 列出文件夹中的所有文件和文件夹
items = os.listdir(folder_path)
# 遍历每个文件和文件夹
dir_list = []
for item in items:
item_path = os.path.join(folder_path, item) # 获取文件或文件夹的完整路径
if os.path.isdir(item_path):
dir_list.append(item_path)
# 递归调用函数打开子文件夹中的文件
# open_files_in_folder(item_path)
return dir_list
在文件夹中找到json文件
def find_json_files(folder_path):
json_files = [] # 存储找到的 JSON 文件
# 列出文件夹中的所有文件和文件夹
items = os.listdir(folder_path)
# 遍历每个文件和文件夹
for item in items:
item_path = os.path.join(folder_path, item) # 获取文件或文件夹的完整路径
if os.path.isfile(item_path) and item.endswith('.json'):
json_files.append(item_path) # 将 JSON 文件路径添加到列表中
elif os.path.isdir(item_path):
# 递归调用函数查找子文件夹中的 JSON 文件
json_files.extend(find_json_files(item_path))
return json_files
遍历每个文件夹并找出其中的 JSON 文件
folder_path = "sop"
files_paths = open_folder(folder_path)
# 遍历每个文件夹并找出其中的 JSON 文件
json_paths = []
for folder_path in files_paths:
json_files = find_json_files(folder_path)
print(f'在文件夹 {folder_path} 中找到的 JSON 文件:')
for json_file in json_files:
print(json_file)
json_paths.append(json_file)
print(json_paths)
判断小写字母
# 判断小写字母
def has_lowercase(s):
return any(c.islower() for c in s)
获取指定路径下的文件名
def get_filename(path):
"""
获取指定路径下的文件名
:param path: 文件路径
:return: 文件名
"""
# 使用os.path.basename()方法获取文件名
filename = os.path.basename(path).split('.')[0]
return filename
获取指定路径的上一级文件夹名
def get_parent_folder(path):
"""
获取指定路径的上一级文件夹名
:param path: 文件路径
:return: 上一级文件夹名
"""
parent_folder = os.path.dirname(path).split('\\')[-1]
return parent_folder