You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python打开含空格文件名的文件失败,求解决方案

解决文件名含空格的文件无法打开问题

Hey there! Let's break down why you're getting that FileNotFoundError even though you've confirmed the file exists, and fix it right away.

问题根源

The issue has nothing to do with the spaces in your filename—though they made the problem noticeable. Here's what's happening:

  • os.listdir() only returns the raw filename string, not the full path to the file.
  • When you call open(filename, ...), Python looks for the file in your current working directory (where you ran the script), not inside the "Subnet folder" directory you're listing. Even files without spaces would fail here!

两种解决方案

方案1:使用pathlib(推荐,更简洁安全)

pathlib is Python's modern path-handling library, and it takes care of path joining and special characters (like spaces) automatically. Here's how to adjust your code:

from pathlib import Path

# Get the full path to your target folder
subnet_folder = Path.cwd() / "Subnet folder"

# Iterate over all items in the folder
for file_path in subnet_folder.iterdir():
    # Only process files (skip subfolders if any)
    if file_path.is_file():
        # Use the full Path object directly with open()
        with open(file_path, 'r', encoding="ISO-8859-1") as f:
            # Add your file processing logic here
            example_content = f.readline()
            print(f"Successfully opened: {file_path.name}")

This works because subnet_folder.iterdir() returns complete Path objects that point directly to each file in the folder—no manual path joining needed.

方案2:手动拼接完整路径(兼容传统os模块)

If you prefer sticking with os.listdir(), you just need to build the full file path before opening it. Use os.path.join() to safely handle spaces and path separators:

import os
from pathlib import Path

# Get the full path to the folder as a string
subnet_folder = str(Path.cwd() / "Subnet folder")

for filename in os.listdir(subnet_folder):
    # Join the folder path with the filename to get the full path
    full_file_path = os.path.join(subnet_folder, filename)
    # Make sure we're dealing with a file (not a subfolder)
    if os.path.isfile(full_file_path):
        with open(full_file_path, 'r', encoding="ISO-8859-1") as f:
            # Your file processing code here
            print(f"Successfully opened: {filename}")

os.path.join() ensures the path is formatted correctly regardless of your operating system, and handles spaces without any extra work.

额外小提示

Always use the with statement when opening files—it automatically closes the file after you're done, preventing resource leaks and unexpected behavior.

内容的提问来源于stack exchange,提问作者Afsheen Taheri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:08:11