创建.txt文件时遭遇Permission Error的问题求助
问题
无法在OneDrive桌面成功创建新的.txt文件,出现奇怪现象:即使指定了文件扩展名,程序却创建了文件夹而非文件,同时触发权限错误提示。已尝试以下方法但未解决:
- 以管理员身份运行IDLE
- 在桌面创建文件夹并将文件保存至该文件夹
- 检查每个.py文件的权限设置
已确认文件名无重复。
代码
desktop_path = pathlib.Path.home() / 'OneDrive' / 'Desktop' print (desktop_path) def save_data(): file_name = last+'_'+first+'_'+'Symptom Checklist 90-R Results.txt' file_path = Path(os.path.join(desktop_path, file_name)) table = tabulate(data, headers="firstrow", tablefmt="grid") os.makedirs(file_path, exist_ok=True) print(file_path) try: with open(file_path,'w') as file: file.write(first_name+"\n"+last_name+"\n"+age+"\n"+birthday+"\n") file.write(table) file.close() except PermissionError: print("You do not have access to create this file.")
打印输出
C:\Users\name\OneDrive\Desktop C:\Users\name\OneDrive\Desktop\__Symptom Checklist 90-R Results.txt You do not have access to create this file.
解决方案
核心问题出在os.makedirs(file_path, exist_ok=True)这一行:os.makedirs是用来创建文件夹的,你把目标文件的完整路径(包含.txt后缀)传给它,导致程序先创建了一个和目标文件同名的文件夹。之后再尝试创建同名文件时,系统会因为该名称已被文件夹占用而触发权限/文件冲突错误。
修正步骤:
- 删除
os.makedirs(file_path, exist_ok=True)这一行(OneDrive桌面路径肯定存在,无需创建);如果是自定义的未知路径,可改为创建文件的父目录:os.makedirs(os.path.dirname(file_path), exist_ok=True) - 用f-string简化字符串拼接,提升代码可读性
- 去掉多余的
file.close()——with open()语句会自动关闭文件
修正后的代码:
from pathlib import Path import os from tabulate import tabulate # 确保已导入tabulate库 desktop_path = Path.home() / 'OneDrive' / 'Desktop' print(desktop_path) def save_data(): # 确保last、first、first_name等变量已正确赋值 file_name = f"{last}_{first}_Symptom Checklist 90-R Results.txt" file_path = Path(os.path.join(desktop_path, file_name)) table = tabulate(data, headers="firstrow", tablefmt="grid") # 如需确保父文件夹存在,启用下面一行(当前场景可省略) # os.makedirs(os.path.dirname(file_path), exist_ok=True) print(file_path) try: with open(file_path,'w', encoding='utf-8') as file: file.write(f"{first_name}\n{last_name}\n{age}\n{birthday}\n") file.write(table) except PermissionError: print("你没有权限创建此文件。")
另外,打印输出中文件名出现__是因为last或first变量为空字符串,需要检查这两个变量是否正确获取了值。
内容的提问来源于stack exchange,提问作者J_D
相关产品推荐
相关产品推荐

