Python 没有这样的文件或目录,即使它确实存在

问题描述 投票:0回答:1

我正在尝试将图像保存到目录中,但即使它在那里,我也没有得到这样的文件或目录,我确保它是在脚本开头创建的,然后检查文件夹以查看它是否在那里:

我的代码:

image_content = image_response.content
image_filename = sanitize_filename(item['caption'])

# Get the gallery folder
gallery_folder = sanitize_filename(soup.find(class_="mw-page-title-main").text)
gallery_folder_path = os.path.normpath(os.path.join('gallery', gallery_folder))

# Make sure the directory exists before saving the image
os.makedirs(gallery_folder_path, exist_ok=True)

# Create the full image path using os.path.join() with gallery_folder_path
image_path = os.path.join(gallery_folder_path, f'{image_filename}.jpg')

# Print the values for debugging
print(f"image_filename: {image_filename}")
print(f"gallery_folder: {gallery_folder}")
print(image_path)
input()
with open(image_path, 'wb') as file:
    file.write(image_content)

控制台输出:

image_filename: The_Farm_by_Jean-Baptiste_Oudry_1750_oil_on_canvas_130_x_212_cm_Louvre._This_Rococo_painting_shows_how_Cottagecore_visuals_are_a_continuation_of_depictions_of_the_traditional_French_and_English_countryside
gallery_folder: Cottagecore
gallery\Cottagecore\The_Farm_by_Jean-Baptiste_Oudry_1750_oil_on_canvas_130_x_212_cm_Louvre._This_Rococo_painting_shows_how_Cottagecore_visuals_are_a_continuation_of_depictions_of_the_traditional_French_and_English_countryside.jpg

Traceback (most recent call last):
  File "C:\Users\PC GAMER\Desktop\Devs\python\scrappers\tvtropes_scrapper\test.py", line 76, in <module>
    with open(image_path, 'wb') as file:
FileNotFoundError: [Errno 2] No such file or directory: 'gallery\\Cottagecore\\The_Farm_by_Jean-Baptiste_Oudry_1750_oil_on_canvas_130_x_212_cm_Louvre._This_Rococo_painting_shows_how_Cottagecore_visuals_are_a_continuation_of_depictions_of_the_traditional_French_and_English_countryside.jpg'

我使用sanotoze功能来清理文件名:

消毒功能: 定义

 sanitize_filename(filename):
    # Remove invalid characters from the filename
    valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
    sanitized_filename = ''.join(c for c in filename if c in valid_chars)
    sanitized_filename = sanitized_filename.replace('/', '_')  # Replace forward slash with underscore
    sanitized_filename = sanitized_filename.replace(' ', '_')  # Replace spaces with underscores
    return sanitized_filename

我已经为这个错误而苦恼了一段时间,我知道这看起来很简单,但我无法弄清楚,问题可能出在哪里?

提前致谢

python file filenotfoundexception
1个回答
0
投票

Python 中的“没有这样的文件或目录”错误可能有多种原因,即使该文件确实存在。以下是此问题的一些常见原因和解决方案:

  1. 文件路径不正确:仔细检查代码中指定的文件路径是否正确,并且文件位于指定的目录中。如果您使用的是 Windows,请确保包含文件的完整路径,包括驱动器号(例如,
    C:\path\to\file.txt
    )。
  2. 文件权限:确保运行Python脚本的用户具有访问文件所需的权限。您可以通过右键单击文件,选择“属性”,然后导航到“安全”选项卡来检查文件的权限。
  3. 操作系统的差异:文件路径在不同操作系统中的表示方式不同。例如,Windows 使用反斜杠 (
    \
    ),而 Linux 和 macOS 使用正斜杠 (
    /
    ) 来分隔文件路径中的目录。确保为您的操作系统使用正确的路径分隔符。

您的具体情况中,问题似乎是由 Windows 和 Linux 中文件路径表示方式的差异引起的。您可以通过将文件路径中的反斜杠 (

\
) 替换为正斜杠 (
/
) 来解决该问题。

我希望这有帮助!如果您还有任何其他问题或需要额外帮助,请随时询问。

© www.soinside.com 2019 - 2024. All rights reserved.