Python pathlib模块

时间:2020-02-23 14:43:08  来源:igfitidea点击:

Python pathlib模块提供了一种面向对象的方法来处理文件和目录。
pathlib模块具有用于Unix和Windows环境的类。
最好的部分是我们不必担心底层操作系统,pathlib模块负责根据操作系统使用适当的类。

Python pathlib路径类

路径是pathlib模块中最重要的类。
这是pathlib模块提供的所有功能的切入点。
它负责实例化基于操作系统的具体路径实现,并使代码独立于平台。

我们来看一些使用pathlib模块的示例。

1.列出目录中的子目录和文件

我们可以使用Path iterdir()函数来遍历目录中的文件。
然后,我们可以使用is_dir()函数来区分文件和目录。

from pathlib import Path

# list subdirectories and files inside a directory
path = Path("/Users/hyman/temp")

subdirs = []
files = []

for x in path.iterdir():  # iterate over the files in the path
  if x.is_dir():  # condition to check if the file is a directory
      subdirs.append(x)
  else:
      files.append(x)

print(subdirs)
print(files)

输出:

[PosixPath('/Users/hyman/temp/spring-webflow-samples'), PosixPath('/Users/hyman/temp/image-optim'), PosixPath('/Users/hyman/temp/jersey2-example')]

[PosixPath('/Users/hyman/temp/test123.py'), PosixPath('/Users/hyman/temp/.txt'), PosixPath('/Users/hyman/temp/xyz.txt'), PosixPath('/Users/hyman/temp/.DS_Store'), PosixPath('/Users/hyman/temp/db.json'), PosixPath('/Users/hyman/temp/Test.java'), PosixPath('/Users/hyman/temp/routes.json'), PosixPath('/Users/hyman/temp/itertools.py')]

如果您在Windows中运行相同的程序,则将获得WindowsPath实例。

2.列出特定类型的文件

我们可以使用Path glob()函数遍历匹配给定模式的文件列表。
让我们使用此功能来打印目录中的所有python脚本。

from pathlib import Path

path = Path("/Users/hyman/temp")

python_files = path.glob('**/*.py')

for pf in python_files:
  print(pf)

输出:

Python Pathlib列表文件

3.解决符号链接到规范路径

我们可以使用resolve()函数将符号链接转换为其规范路径。

py2_path = Path("/usr/bin/python2.7")

print(py2_path)
print(py2_path.resolve())

输出:

/usr/bin/python2.7
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7

4.检查文件或者目录是否存在

如果路径存在,则Path exist()函数将返回True,否则返回False。

path = Path("/Users/hyman/temp")
print(path.exists())  # True

path = Path("/Users/hyman/temp/random1234")
print(path.exists())  # False

5.打开和读取文件内容

我们可以使用Path open()函数打开文件。
它返回一个文件对象,如内置的open()函数。

file_path = Path("/Users/hyman/temp/test.py")

if file_path.exists() and file_path.is_file():
  with file_path.open() as f:
      print(f.readlines())

输出:

['import os\n', '\n', 'print("Hello World")\n']

6.获取文件信息

Path对象的stat()函数进行stat()系统调用并返回结果。
输出与os模块的stat()函数相同。

file_path = Path("/Users/hyman/temp/test.py")

print(file_path.stat())

输出:

os.stat_result(st_mode=33188, st_ino=8623963104, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=32, st_atime=1566476310, st_mtime=1566476242, st_ctime=1566476242)

7.获取文件或者目录名称

我们可以使用"名称"属性从路径对象获取文件名。

print(Path("/Users/hyman/temp/test.py").name)
print(Path("/Users/hyman/temp/").name)
print("Path without argument Name :", Path().name)

输出:

test.py
temp
Path without argument Name :

8.创建和删除目录

我们可以使用mkdir()函数创建目录。
我们可以使用rmdir()删除一个空目录。
如果有文件,那么我们必须先删除它们,然后再删除目录。

directory = Path("/Users/hyman/temp/temp_dir")
print(directory.exists())  # False
directory.mkdir()
print(directory.exists())  # True
directory.rmdir()
print(directory.exists())  # False

9.更改文件模式

file = Path("/Users/hyman/temp/test.py")
file.chmod(0o777)

chmod()函数的行为与os.chmod()函数相同,以更改文件许可权。

10.获取文件组和所有者名称

file = Path("/Users/hyman/temp/test.py")
print(file.group())  # staff
print(file.owner())  # hyman

11.展开~至规范路径

path = Path("~/temp")
print(path)  # ~/temp
path = path.expanduser()
print(path)  # /Users/hyman/temp

12. CWD和原路

print(Path.cwd())
print(Path.home())

输出:

/Users/hyman/Documents/PycharmProjects/PythonTutorials/hello-world
/Users/hyman

13.连接两条路径

path = Path.home()
path = path.joinpath(Path("temp"))
print(path)  # /Users/hyman/temp

14.创建一个空文件

就像Unix touch命令一样,Path具有touch()函数来创建一个空文件。
您应该具有创建文件的权限。
否则,将不会创建文件,并且不会引发任何错误。

new_file = Path("/Users/hyman/temp/xyz.txt")
print(new_file.exists())  # False
new_file.touch()
print(new_file.exists())  # True