今天写脚本时想读文件数据,但是脚本和文件不在同一目录下,菜鸟经调试多次终于成功。
以下是代码分享。
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}")