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

如何在Python3中使用跨平台文件路径读写文件并解决UnicodeError?

解决文件读写的UnicodeError及跨平台路径兼容问题

嘿,我来帮你搞定这俩问题——绝对路径触发的UnicodeError,还有跨平台文件路径的通用写法,这在Python文件操作里都是高频踩坑点。

一、先搞定UnicodeError

这个报错大概率是路径里包含非ASCII字符(比如中文、特殊符号),或者你手动写路径时转义处理不当导致的。给你几个靠谱的解决方向:

  • 用原始字符串避免转义:Windows路径里的反斜杠容易触发转义,加个r前缀变成原始字符串就好,比如:
    input_path = r"C:\Users\张三\Documents\input_file.txt"
    
  • 用pathlib处理路径(强推):这个模块是Python 3.4+自带的,会自动处理系统的路径编码问题,完全不用你手动纠结字符串编码:
    from pathlib import Path
    
    input_file = Path("C:/Users/张三/Documents/input_file.txt")
    
  • 指定编码打开文件:如果是Windows老环境,文件路径可能用GBK编码,你可以手动指定编码来打开:
    with open(input_path, 'r', encoding='gbk') as f:
        content = f.read()
    

二、跨平台路径的通用写法(兼容Linux/Mac/Windows)

Python 3里有两种非常成熟的方案,完全不用你手动写斜杠/反斜杠:

1. 使用pathlib(最简洁优雅)

这是现在官方推荐的方式,面向对象的写法,用/就能拼接路径,自动适配不同系统的分隔符:

from pathlib import Path

# 拼接路径:不管是Windows还是Linux/Mac,直接用 / 就行
data_folder = Path.home() / "Documents" / "test_files"
input_file = data_folder / "input_file.txt"
output_file = data_folder / "output_file.txt"

# 先确保目录存在(如果不存在就创建,父目录也一起创建)
data_folder.mkdir(parents=True, exist_ok=True)

# 你的读写逻辑,记得指定encoding避免编码问题
with open(input_file, 'r', encoding='utf-8') as f_in:
    content = f_in.read()

with open(output_file, 'w', encoding='utf-8') as f_out:
    f_out.write(content)

2. 使用os.path(兼容更早Python版本)

如果你的项目要兼容Python 3.4之前的版本,就用os.path.join()来拼接路径,它会自动识别当前系统用什么分隔符:

import os

# 拼接路径
home_dir = os.path.expanduser("~")  # 获取用户主目录
data_folder = os.path.join(home_dir, "Documents", "test_files")
input_file = os.path.join(data_folder, "input_file.txt")
output_file = os.path.join(data_folder, "output_file.txt")

# 创建目录(如果不存在)
os.makedirs(data_folder, exist_ok=True)

# 读写文件
with open(input_file, 'r', encoding='utf-8') as f_in:
    content = f_in.read()

with open(output_file, 'w', encoding='utf-8') as f_out:
    f_out.write(content)

三、最后验证你的核心逻辑

你的读写逻辑本身是对的,只是要注意两个细节:

  • 打开文件时一定要指定encoding参数,不同系统的默认编码不一样,不指定容易踩坑
  • 可以加个判断确保输入文件存在,避免触发FileNotFoundError:
    if input_file.exists():  # 如果用pathlib的话
        # 执行读写
    else:
        print("输入文件找不到哦!")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:21:20