python书写文件路径

今天写脚本时想读文件数据,但是脚本和文件不在同一目录下,菜鸟经调试多次终于成功。

以下是代码分享。

import os

# 脚本的绝对路径
script_abs_path = r'C:\a\jiaoben'
script_dir = os.path.dirname(script_abs_path)

# 目标文件的绝对路径
target_abs_path = r'C:\b\xx.csv'

# 计算相对路径
relative_path = os.path.relpath(target_abs_path, start=script_dir)

# 输出相对路径
print(f"Relative path: {relative_path}")

# 构建绝对路径
file_path = os.path.join(script_dir, relative_path)

# 输出构建的绝对路径
print(f"Full file path: {file_path}")

# 检查文件是否存在
if os.path.exists(file_path):
    # 检查是否有权限读取文件
    if os.access(file_path, os.R_OK):
        # 使用正确的文件句柄变量名
        try:
            with open(file_path, mode='r', encoding='utf-8') as file:
                content = file.read()
                print(content)  #输出文件内容
        except Exception as e:
            print(f"Error opening the file: {e}")
    else:
        print("Insufficient permissions to read the file.")
else:
    print("The file does not exist.")

# 输出脚本所在目录的绝对路径
print(f"Script directory: {script_dir}")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值