Python中硬编码绝对路径可用但存入变量调用报文件不存在错误
错误原因
你的代码存在4个核心问题,直接触发文件找不到报错:
- os.walk遍历逻辑错误:
os.walk返回的roots为当前遍历到的目录绝对路径,files是roots目录下的所有文件名,不需要额外嵌套遍历dirs列表,你当前的路径拼接逻辑强行把子目录名加入路径,生成的路径本身就是无效的 - 变量引用错误:你拼接完路径后赋值给了
file_path变量,但打开文件时用的是未定义的full_path变量,从报错信息看你实际运行的代码甚至直接用纯文件名x打开文件,只会在程序运行的当前工作目录查找文件,自然找不到 - 异步逻辑错误:异步代码中使用同步的
time.sleep会阻塞整个机器人的事件循环,应该用异步休眠 - 语法缩进错误:
list_dir函数中调用dir_walk的行没有正确缩进,不会按预期随循环执行
修正后完整代码
import os import discord import asyncio from discord.ext import commands client = commands.Bot(command_prefix = '!!') # 待上传根目录 locations = [ '/root/discord/', '/home/discord', ] # 不上传的文件扩展名 bad_files = [ 'viminfo', 'txt', 'sh', 'bat', ] async def dir_walk(ctx,p): # 提前检查目录有效性 if not os.path.isdir(p): await ctx.send(f"目录{p}不存在或无访问权限") return for roots, dirs, files in os.walk(p): for x in files: # 更稳妥的扩展名判断方式 ext = os.path.splitext(x)[-1].lower().lstrip('.') if ext in bad_files or ext == '': continue try: file_path = os.path.join(roots, x) # 用上下文管理器自动关闭文件句柄 with open(file_path, 'rb') as f: await ctx.send(os.path.basename(roots), file = discord.File(f, filename = x)) await asyncio.sleep(5) except Exception as e: print(f"文件{file_path}上传失败:{str(e)}") await asyncio.sleep(5) @client.command(pass_context=True, name="walk") async def list_dir(ctx): for x in locations: await dir_walk(ctx, x) client.run('你的机器人Token')
额外优化建议
- 尽量不要用
/root目录下的资源,普通权限运行的机器人进程大概率没有root目录访问权限,会触发权限报错 - 上传前可以加文件大小判断,普通Discord服务器单文件上传上限为8MB,超过会上传失败
- 可以添加已上传文件记录,避免重复上传相同文件
内容的提问来源于stack exchange,提问作者Taux1c
相关产品推荐
相关产品推荐

