简体   繁体   中英

How to switch from Path to os.path and vice versa?

Whenever I want to work with files or directories, the approach of today is to use pathlib . pathlib is great, convenient, easy to use, and os independent.

However, some libraries still expect me to use os.path . How can I transform my Path to the old-school version?

What should I do with my p in the following example?

from pathlib import Path
p = Path.cwd()
some_old_function(p)   # <---- error

The phrase some libraries still expect me to use os.path seem to confuse you. os.path simply treats paths as strings - as opposed to pathlib which treats them as a specialized object in the OOP approach.

So a simple str(p) should solve your problem.

Just convert it to string.

from pathlib import Path
p = Path.cwd()
some_old_function(str(p))

Now I also understand, why it was necessary to introduce pathlib ...

You need to convert your PosixPath to a string, os.path expect a string. You can use as_posix or str.

In [1]: from pathlib import Path

In [2]: Path.cwd()
Out[2]: PosixPath('/usr/home/ericbsd')

In [3]: Path.cwd().as_posix()
Out[3]: '/usr/home/ericbsd'

In [4]: str(Path.cwd())
Out[4]: '/usr/home/ericbsd

here how it would look like with as_posix.

from pathlib import Path
p = Path.cwd().as_posix()
some_old_function(p)

As for converting os.path to pathlib you can use PosixPath.

In [1]: from pathlib import PosixPath

In [2]: import os

In [3]: os.getcwd()
Out[3]: '/usr/home/ericbsd'

In [4]: PosixPath(os.getcwd())
Out[4]: PosixPath('/usr/home/ericbsd')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM