无法在 Python 3 中打开文本文件:Unicode 错误

问题描述

我在 Python 3.8 中打开一个简单的文本文件时遇到问题。我设置了一个简单的测试。

这是我的测试代码

import os

file_path = "c:\Users\username\Documents\folder1\some_file.txt"

with open(file_path,'r') as f:
    for line in f:
        print(line)

我收到以下错误Unicode 错误“unicodeescape”编解码器无法解码位置 2-3 中的字节。

我读过其他关于在文件路径前面放一个 'r' 的帖子,当我这样做时,我得到一个 “没有这样的文件或目录:'c:\Users\username\Documents\ folder1\some_file.txt'

import os

file_path = r"c:\Users\username\Documents\folder1\some_file.txt"

with open(file_path,'r') as f:
    for line in f:
        print(line)

我也试过在路径 c:\\Users\\username\\Documents\\folder1\\some_file.txt 中使用双反斜杠,但也没有用。

我已尝试使用 pathlib 进行测试,但仍然出现 unicode 错误

from pathlib import Path

file_path = "c:\Users\username\Documents\folder1\some_file.txt"

file_path = Path(file_path).absolute()

with open(fpath,'r',encoding='utf-8') as f:
    line = f.readlines()
    for line in f:
        print(line)

解决方法

在您的第一个示例中, file_path = "c:\Users\username\Documents\folder1\some_file.txt" \Users 中的 \U 表示一个 Unicode 转义序列,它试图将 sers 解码为一个 Unicode 字符,但事实并非如此。

在我的机器上,双反斜杠似乎有效 - 但当然我在那个路径上没有文本文件,所以我无法真正测试。

首先尝试对 \U 使用双反斜杠。

,

更多信息:

正如 Andrew Kaluzniacki's answer 正确指出的,问题在于路径字符串。

使用 pathlib.Path

为了避免麻烦 Windows 路径和分隔符,可以选择始终使用正斜杠,因为 open() 和 Windows 都有处理此问题的机制。

然而,为了向后兼容和健壮性,使用标准库中的 pathlib.Path 可以说更好(仍然使用正斜杠作为路径分隔符)。 pathlib 会自动将文件路径转换为适合您操作系统的路径。

最后,os.path.filesep() 返回主机操作系统的文件分隔符。

人们遇到类似问题的另一个潜在原因

文件中可能存在操作系统默认编码未涵盖的字符。

通过将不同的编码传递给 encodingopen() 参数来尝试其他编码。

您可以尝试 open(file_path,'r',encoding='utf-8'),尽管这应该是 Windows 10 的默认设置,前提是您的操作系统基于您的文件路径示例。

如果不知道文件中的内容,就很难知道哪种编码有效。

from pathlib import Path

fpath = Path(fpath).absolute()
# ^^ absolute() is not necessary if
# the file is in the same directory
# as the calling Python script
# and you just pass a filename.

with open(fpath,encoding='utf-8') as filehandle:
    do_something_with(filehandle)