【发布时间】:2022-01-08 02:01:15
【问题描述】:
我正在尝试编写一个 python 机器人,它只会将目录中的大量文件上传到服务器。 (主要是带有一些屏幕截图的游戏剪辑。)问题是当我动态传递文件路径时,我得到一个文件未找到错误。通过硬编码时,它工作正常。我已经打印甚至发送了不和谐的文件路径,它是正确的。尝试了 .strip() 和 .encode('unicode-escape') 以及其他各种选项,但没有找到任何可行的方法。这让我有点不解。有什么想法吗?
import os
import discord
import time
from discord.ext import commands
client = commands.Bot(command_prefix = '!!')
#locations to upload
locations = [
'/root/discord/',
'/home/discord',
]
#file types to not upload
bad_files = [
'viminfo',
'txt',
'sh',
'',
'bat',
]
#walk through directory and upload files
async def dir_walk(ctx,p):
for roots,dirs,files in os.walk(p):
for i in dirs:
for x in files:
#check to see if file extension matches one listed to not upload.
if x.split('.')[-1] in bad_files:
pass
else:
try:
#upload files
file_path = os.path.join(roots,i,x)
f = open(full_path,'rb')
await ctx.send(i,file = discord.File(f,filename = x))
time.sleep(5)
except:
raise
time.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('')
回溯是:
Ignoring exception in command walk:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", li ne 85, in wrapped
ret = await coro(*args, **kwargs)
File "newwalk.py", line 50, in list_dir
await dir_walk(ctx,x)
File "newwalk.py", line 40, in dir_walk
f = open(x,'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'ss dec_2019_1_20_0008.jpg'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", lin e 939, in invoke
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", li ne 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", li ne 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Fil eNotFoundError: [Errno 2] No such file or directory: 'ss dec_2019_1_20_0008.jpg'
【问题讨论】:
-
如果可以,请同时发布错误/回溯。就像另一个代码块或 pastebin 链接一样。
-
当然,我完全忘记了这一点。我现在已经添加了。
-
我稍微更改了代码,但这与我使用上面显示的内容时抛出的异常相同。唯一的区别是当我复制异常时,我正在尝试 os.chdir(os.path.join(roots,i)) 然后使用 f = open(x,'rb') 和以前一样,我只有完整路径文件 full_path=os.path.join(roots,i,x) open(full_path,'rb')
-
嗯,我建议有一个
except FileNotFoundError:块并在其中将每个未找到的full_path添加到列表中。然后打印出来看看有没有问题。我还注意到在locations中,第二个条目没有以/结尾。我怀疑它会导致错误,但值得一试。与此同时,我会做一些测试并尝试帮助解决这个问题 -
所以我能够通过一个奇怪的修复让它在我的机器人上工作。我不知道这是否对你有用,但基本上我拆分了
full_path并且只使用了实际的文件名。所以在做full_path = os.path.join(roots,i,x)之后,试试full_path = full_path.split("/")[-1]。然后f = open(full_path,'rb')。如果令人困惑,我可以发布我拥有的完整代码。
标签: python-3.x path discord.py python-os