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

使用os函数无法访问CSV对比脚本文件的问题求助

解决Python无法定位CSV文件:路径显示正确但os.path.exists()返回False的问题

问题场景

基于CSV对比需求编写的Python脚本中,print(actual)输出了正确的文件路径,但os.path.exists(actual)返回False,自定义的权限检查函数显示文件无读、写、执行权限。手动修改权限(os.chmod())无效,且本地系统中已拥有该文件的全部权限,运行环境为JupyterLab,项目文件夹位于桌面。

相关代码

调试用代码:

import pandas as pd
import os
import json
import sys

def check_file_permissions(file_path):
    if os.access(file_path, os.R_OK):
        print(f"Read permission is granted for file: {file_path}")
   
    else:
        print(f"Read permission is not granted for file: {file_path}")
    
    if os.access(file_path, os.W_OK):
        print(f"Write permission is granted for file: {file_path}")
   
    else:
        print(f"Write permission is not granted for file: {file_path}")
    
    if os.access(file_path, os.X_OK):
        print(f"Execute permission is granted for file: {file_path}")
   
    else:
        print(f"Execute permission is not granted for file: {file_path}")

cwd = os.getcwd()
cwwd = os.path.join(cwd, "Projects", "compare-csv")
input_JSON = os.path.join(cwwd, "data", "input.json")

input_data = json.load(open(input_JSON))
data = input_data ["info"]

for info in data:
    expected = os.path.join(cwwd, "inputs", "expected", info["expected"])
    actual = os.path.join(cwwd, "inputs", "actual", info["actual"])
    print(actual)
    
    diff = os.path.join(cwwd, "inputs", "diff", info["diff"])
    summary = os.path.join(cwwd, "inputs", "diff", info["summary"])
    identity = info["identity"]
    
    # os.chmod(actual, 777)
    check_file_permissions(actual)
    
    actual_path = os.path.exists(actual)
    print(actual_path)

JSON配置文件:

{
    "info": [{
        "description": "Placeholder.",
        "expected": "user_info_expected.csv",
        "actual": "user_info_actual.csv",
        "diff": "user_info_diff.csv",
        "summary": "user_info_summary.csv",
        "identity": "id"
    }]
}

解决方案与排查步骤

1. 验证JupyterLab的实际工作目录

JupyterLab的os.getcwd()返回的是启动Jupyter时的目录,而非脚本所在目录。直接打印绝对路径验证:

print("Absolute actual path:", os.path.abspath(actual))

将输出的路径复制到文件管理器中打开,确认文件是否真的存在。如果路径错误,手动指定项目的绝对路径(如/Users/xxx/Desktop/Projects/compare-csv或C:\Users\xxx\Desktop\Projects\compare-csv)替代os.getcwd()的拼接逻辑。

2. 检查中间目录是否存在

os.path.join()仅拼接路径,不会自动创建中间目录。如果inputs/actual目录不存在,即使文件名正确,os.path.exists()也会返回False。添加目录检查与创建:

# 检查并创建actual文件所在的目录
actual_dir = os.path.dirname(actual)
if not os.path.exists(actual_dir):
    print(f"Creating directory: {actual_dir}")
    os.makedirs(actual_dir, exist_ok=True)

3. 绕过os.access直接测试文件读取

os.access()的权限检查可能受Jupyter运行上下文影响,直接尝试打开文件获取具体错误:

try:
    with open(actual, 'r') as f:
        print("Successfully opened the file")
except Exception as e:
    print(f"Error opening file: {str(e)}")

通过报错信息(如FileNotFoundError、PermissionError、UnicodeDecodeError)精准定位问题。

4. 检查路径大小写与特殊字符

  • Windows系统默认不区分大小写,但如果文件名实际为User_Info_Actual.csv而配置里写的是user_info_actual.csv,部分场景下会导致识别失败;
  • 路径含空格或非ASCII字符时,尝试用原始字符串格式,或修改路径为无特殊字符的格式。

5. 确认JupyterLab的运行权限

Windows环境下右键以管理员身份启动JupyterLab;Mac/Linux环境下尝试用sudo启动Jupyter(注意虚拟环境路径),排除进程权限不足的问题。

内容的提问来源于stack exchange,提问作者AJ Athena

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:55:29