在更改文件名字关于PermissionError: [WinError 5] 拒绝访问。
我尝试了更改虚拟环境权限,尝试了更改文件属性为只读都没办法解决
for i in filename_lst:
if '.' in i:
filepath = os.path.join(path, i)
target_dir = os.path.splitext(filepath)[0] # 移除文件扩展名得到目标目录
unzip(filepath, target_dir)
# 假设您的 JSON 数据存储在一个名为 "article.json" 的文件中
with open(target_dir+"/output.json", "r",encoding='utf-8') as f:
data = json.load(f)
# 从 JSON 数据中提取标题
title = data["title"]
current_file_name=target_dir
new_file_name=path+'/'+title
os.rename(current_file_name, new_file_name)
后来我发现title可能有违法字符
for i in filename_lst:
if '.' in i:
filepath = os.path.join(path, i)
target_dir = os.path.splitext(filepath)[0] # 移除文件扩展名得到目标目录
unzip(filepath, target_dir)
# 假设您的 JSON 数据存储在一个名为 "article.json" 的文件中
with open(target_dir+"/output.json", "r",encoding='utf-8') as f:
data = json.load(f)
# 从 JSON 数据中提取标题
title = data["title"]
current_file_name=target_dir
new_file_name=path+'/'+title
import re
def clean_directory_name(dir_name):
# 移除Windows文件名中不允许的字符
return re.sub(r'[<>:"/\\|?*]', '', dir_name)
# 假设 title 是从 JSON 中提取的标题
title = "Data Augmentation using LLMs: Data Perspectives, Learning Paradigms and Challenges"
clean_title = clean_directory_name(title)
new_file_name = os.path.join(path, clean_title)
# 现在尝试重命名
try:
os.rename(target_dir, new_file_name)
except PermissionError as e:
print(f"Permission denied when renaming {target_dir} to {new_file_name}: {e}")
except Exception as e:
print(f"An error occurred: {e}")
发现没问题了准备把这个clean函数放入循环
for i in filename_lst:
if '.' in i:
filepath = os.path.join(path, i)
target_dir = os.path.splitext(filepath)[0] # 移除文件扩展名得到目标目录
unzip(filepath, target_dir)
# 假设您的 JSON 数据存储在一个名为 "output.json" 的文件中
json_file_path = os.path.join(target_dir, "output.json")
if os.path.exists(json_file_path):
try:
with open(json_file_path, "r", encoding='utf-8') as f:
data = json.load(f)
# 从 JSON 数据中提取标题
title = data["title"]
clean_title = clean_directory_name(title)
new_file_name = os.path.join(path, clean_title)
# 检查是否已存在同名目录
if not os.path.exists(new_file_name):
os.rename(target_dir, new_file_name)
else:
print(f"Directory '{new_file_name}' already exists. Skipping rename.")
except json.JSONDecodeError as e:
print(f"Error decoding JSON from {json_file_path}: {e}")
except PermissionError as e:
print(f"Permission denied when renaming {target_dir} to {new_file_name}: {e}")
except Exception as e:
print(f"An error occurred: {e}")
结果还是PermissionError: [WinError 5] 拒绝访问。
最后发现 可能是with open使得打开了文件夹 所以导致没有办法重命名 就将rename写到open外面
for i in filename_lst:
if '.' in i:
filepath = os.path.join(path, i)
target_dir = os.path.splitext(filepath)[0] # 移除文件扩展名得到目标目录
unzip(filepath, target_dir)
with open(target_dir+"/output.json", "r",encoding='utf-8') as f:
data = json.load(f)
# 从 JSON 数据中提取标题
title = data["title"]
clean_title=clean_directory_name(title)
current_file_name=target_dir
new_file_name=path+'/'+title
new_file_name = os.path.join(path, clean_title)
os.rename(current_file_name, new_file_name)
解决