尝试在指定目录创建文件时触发PermissionError的问题排查
问题分析与解决
你的核心错误是用open()函数尝试打开目录,而open()只能用于操作文件,不能直接打开文件夹,这才触发了PermissionError。
看你的代码:
with open(dir_path, 'x') as f: f.write(file_path, os.path.basename(file_path))
这里dir_path是'testing',也就是你创建的文件夹,你试图把它当作文件打开,自然会报错。
修正后的代码
要在指定目录创建文件,需要先拼接目录路径和文件名,得到完整的文件路径,再用open()操作:
import os # 创建目录(如果不存在) if not os.path.isdir('testing'): os.mkdir('testing') dir_path = 'testing' file_name = 'foo.mp3' # 拼接完整文件路径 full_file_path = os.path.join(dir_path, file_name) # 创建并写入文件(模式'x'确保文件不存在才创建) with open(full_file_path, 'x') as f: # 如果是要写入mp3内容,这里应该替换为实际的音频数据 # 示例:写入空内容(如果只是创建空文件) pass
批量创建mp3文件的思路
如果要批量添加,只需循环处理文件名列表,重复拼接路径和创建文件的步骤:
import os dir_path = 'testing' # 确保目录存在,已存在时不会报错 os.makedirs(dir_path, exist_ok=True) # 批量文件名列表 mp3_files = ['file1.mp3', 'file2.mp3', 'file3.mp3'] for file_name in mp3_files: full_path = os.path.join(dir_path, file_name) with open(full_path, 'x') as f: # 写入对应的mp3数据,比如从其他文件读取后写入 # 示例:如果是复制已有文件,可以用shutil.copy pass
注意:open()的write()方法只接受一个参数(要写入的内容),你原来的f.write(file_path, os.path.basename(file_path))写法是错误的,会触发参数数量错误。如果是要写入mp3的实际内容,需要把音频数据传入write()。
内容的提问来源于stack exchange,提问作者hbhutta
相关产品推荐
相关产品推荐

