为什么 Python2 和 Python3 对同一个 windows 目录的处理方式不同? [英] Why Python2 and Python3 treat same windows directory differently?

查看:46
本文介绍了为什么 Python2 和 Python3 对同一个 windows 目录的处理方式不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的windows语言是中文.为了说明我的观点,我使用包 pathlib.

My windows language is Chinese. To illustrate my point, I use package pathlib.

from pathlib import *
rootdir=Path(r'D:\新建文件夹')
print(rootdir.exists())

Python2.7 我得到 False

Python3 我得到 True

有什么想法吗?感谢您的建议.

Any ideas?Thanks for any advice.

对于Python2.7,你可以用pip install pathlib"安装pathlib

For Python2.7,you can install pathlib with "pip install pathlib"

推荐答案

在 Python 3 中,字符串默认为 Unicode.在 Python 2 中,它们是在源文件编码中编码的字节字符串.在 Python 2 中使用 Unicode 字符串.

In Python 3 strings are Unicode by default. In Python 2, they are byte strings encoded in the source file encoding. Use a Unicode string in Python 2.

还要确保声明源文件编码并确保源文件以该编码保存.

Also make sure to declare the source file encoding and make sure the source is saved in that encoding.

#coding:utf8
from pathlib import *
rootdir=Path(ur'D:\新建文件夹')
print(rootdir.exists())

这篇关于为什么 Python2 和 Python3 对同一个 windows 目录的处理方式不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆