新式的pathlib module https://docs.python.org/3/library/pathlib.html(在 Python >= 3.4 中可用)非常适合处理类似路径的对象(Windows 和其他操作系统)。
这是路径 - 一路向下的路径 https://xkcd.com/1416/
为了简化:您可以将任何路径(目录和文件路径对象被视为完全相同)构建为对象,该对象可以是绝对路径对象 or a 相对路径对象。您可以使用原始字符串来创建复杂的路径(即r'string'
) and pathlib
会非常宽容。但是,请注意,有比原始字符串更好的方法来构建路径(请参阅下文)。
以下是示例:
from pathlib import Path
Path(r'c:\temp\foo.bar') # absolute path
Path(r'c:/temp/foo.bar') # same absolute path
Path('foo.bar') # different path, RELATIVE to current directory
Path('foo.bar').resolve() # resolve converts to absolute path
Path('foo.bar').exists() # check to see if path exists
请注意,如果您使用的是 Windowspathlib
原谅您在第二个示例中使用“错误的斜杠”。请参阅最后的讨论,了解为什么您应该always使用正斜杠。
简单显示一些有用的路径(例如当前工作目录和用户主目录)的工作方式如下:
# Current directory (relative):
cwd = Path() # or Path('.')
print(cwd)
# Current directory (absolute):
cwd = Path.cwd()
print(cwd)
# User home directory:
home = Path.home()
print(home)
# Something inside the current directory
file_path = Path('some_file.txt') # relative path; or
file_path = Path()/'some_file.txt' # also relative path
file_path = Path().resolve()/Path('some_file.txt') # absolute path
print(file_path)
要向下导航文件树,您可以执行以下操作。请注意,第一个对象,home
, is a Path
其余的只是字符串:
some_person = home/'Documents'/'Project Documentation'/'personica.txt' # or
some_person = home.join('Documents','Project Documentation','personica.txt')
要读取位于某个路径的文件,您可以使用它的open
方法而不是open
功能:
with some_person.open() as f:
dostuff(f)
但您也可以直接抓取文本!
contents = some_person.read_text()
content_lines = contents.split('\n')
...并直接写入文字!
data = '\n'.join(content_lines)
some_person.write_text(data) # overwrites existing file
检查它是否是文件或目录(并且存在),如下所示:
some_person.is_dir()
some_person.is_file()
创建一个新的空文件而不打开它,如下所示(默默地替换任何现有文件):
some_person.touch()
制作文件仅当它不存在时, use exist_ok=False
:
try:
some_person.touch(exist_ok=False)
except FileExistsError:
# file exists
新建一个目录(在当前目录下,Path()
) 像这样:
Path().mkdir('new/dir') # get errors if Path()/`new` doesn't exist
Path().mkdir('new/dir', parents=True) # will make Path()/`new` if it doesn't exist
Path().mkdir('new/dir', exist_ok=True) # errors ignored if `dir` already exists
通过以下方式获取路径的文件扩展名或文件名:
some_person.suffix # empty string if no extension
some_person.stem # note: works on directories too
Use name
对于路径的整个最后部分(主干和扩展名,如果存在):
some_person.name # note: works on directories too
使用重命名文件with_name
方法(返回相同的路径对象但具有新的文件名):
new_person = some_person.with_name('personica_new.txt')
您可以像这样使用来迭代目录中的所有“东西”iterdir
:
all_the_things = list(Path().iterdir()) # returns a list of Path objects
侧边栏:反斜杠 (\
)
在路径字符串中使用反斜杠时要小心,尤其是ending带有反斜杠的路径。与any字符串,Python 会读取它终止反斜杠作为转义字符即使在原始输入模式下。观察:
>>> r'\'
File "<stdin>", line 1
r'\'
^
SyntaxError: EOL while scanning string literal
因此,如果您不知道这个问题,这将给出一个非常神秘的错误消息:
>>> Path(r'C:\')
File "<stdin>", line 1
Path(r'\')
^
SyntaxError: EOL while scanning string literal
这个错误的原因是\'
假定为单引号在字符串中。这工作正常:'\''
(第二个单引号结束字符串)。
如果您坚持使用反斜杠,请务必使用原始输入模式,否则您会遇到问题。例如,'\t'
字符代表一个制表符。所以当你这样做时(没有原始输入):
>>> Path('C:\temp')
您正在将制表符放入路径中。这是完全合法的,Python 不会抱怨,除非你做了一些导致 Windows 尝试将其转换为真正的 Windows 路径的操作:
>>> Path('C:\temp').resolve()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\temp'
如果您不知道发生了什么,这也是一个非常神秘的错误!在处理路径时最好完全避免使用反斜杠字符。
预防你的问题
当您创建文件并错误地添加了双扩展名时,出现了您的问题。为了防止这个问题,使用pathlib
, 使用touch
文件制作方法:
some_person = Path.home()/'Documents'/'Project Documentation'/'personica.txt'
some_person.touch()