【问题标题】:Absolute path works when hardcoded but not when stored in variable in python绝对路径在硬编码时有效,但在 python 中存储在变量中时无效
【发布时间】: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


【解决方案1】:

我设法找到了一种方法来做到这一点。这将需要更多的工作,但我稍微更改了代码。在这里。

import os
import discord
import time
from discord.ext import commands
client = commands.Bot(command_prefix = '!!')


#locations to upload
locations = [

        '',


        ]
#file types to not upload
good_files = [
    'png',
    'jpg',
    'jpeg',
    'mp4',
    'mpg',
    'mpeg',
    'wav',
    'flv',
    'mov',
    'gif',
    'tif',
    'bmp',




        ]

#walk through directory and upload files
async def dir_walk(ctx,p):
    for roots,dirs,files in os.walk(p):
        for i in dirs:
            os.chdir(os.path.join(roots,i))
            for x in os.listdir('.'):
                if os.path.isfile(x):
                    if x.split('.')[-1] in good_files:
                        try:
                            with open(x,'rb') as f:
                                await ctx.send(i,file = discord.File(f,filename = x))
                                time.sleep(1)
                        except:
                            pass





@client.command(pass_context=True, name="walk")
async def list_dir(ctx):
    for x in locations:
        await dir_walk(ctx,x)

client.run('')

【讨论】:

    猜你喜欢
    • 2012-05-20
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    相关资源
    最近更新 更多