Python:os.path.isfile无法识别以数字开头的文件 [英] Python: os.path.isfile won't recognise files beginning with a number

查看:359
本文介绍了Python:os.path.isfile无法识别以数字开头的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试将os.path.isfileos.path.exists合并到我的代码中,从而在搜索以字母开头的文件名时成功找到某些常规文件(pdf,png).

So, I'm trying to incorporate os.path.isfile or os.path.exists into my code with success in finding certain regular files(pdf,png) when searching for filenames that begin with a letter.

我正在使用的文件命名标准(由于用户而不能更改)以数字开头,随后无法使用相同的方法找到.有什么方法可以使这些文件可以被.isfile.exists发现?

The file naming standard that I'm using (and can't change due to the user) starts with a number and subsequently can't be found using the same method. Is there a way that I can make these files discoverable by .isfile or .exists?

我要搜索的文件是.txt文件.

The files I'm searching for are .txt files.

    os.path.isfile("D:\Users\spx9gs\Project Work\Data\21022013AA.txt")

    os.path.isfile("D:\Users\spx9gs\Project Work\Data\AA21022013.txt")

返回:

错误

推荐答案

您需要使用原始字符串,或转义反斜杠.在文件名中:

You need to use raw strings, or escape your backslashes. In the filename:

"D:\Users\spx9gs\Project Work\Data\21022013AA.txt"

\210将被解释为八进制转义码,因此您将无法获得正确的文件名.

the \210 will be interpreted as an octal escape code so you won't get the correct filename.

这两种方法都可以使用:

Either of these will work:

r"D:\Users\spx9gs\Project Work\Data\21022013AA.txt"
"D:\\Users\\spx9gs\\Project Work\\Data\\21022013AA.txt"

这篇关于Python:os.path.isfile无法识别以数字开头的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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