Platform-independent file paths?

2020-01-29 05:33发布

How can I use a file inside my app folder in Python? Platform independent of course... something similar to this:

#!/bin/sh
mypath=${0%/*}
LIBDIR=$mypath/modules

4条回答
聊天终结者
2楼-- · 2020-01-29 05:56

In Python 3.4+ you can use pathlib:

from pathlib import Path

libdir = Path(__file__).resolve().with_name('modules')

How it works: the __file__ attribute contains the pathname of the file from which the module was loaded. You use it to initialize a Path object , make the path absolute using the resolve() method and replace the final path component using the with_name() method.

查看更多
Ridiculous、
3楼-- · 2020-01-29 06:01
import os
os.path.join(os.path.curdir, 'file.name')

or

import os
os.path.join(os.path.dirname(__file__), 'file.name')

depending upon whether it's a module (2) or a single script (1), and whether you're invoking it from the same directory (1), or from a different one (2).

Edit

Looking at the "attempt" you have in your question, I'd guess that you'd want (1).

查看更多
走好不送
4楼-- · 2020-01-29 06:10

You can use os.path and its functions, which take care of OS-specific paths:

>>> import os
>>> os.path.join('app', 'subdir', 'dir', 'filename.foo')
'app/subdir/dir/filename.foo'

On Windows, it should print out with backslashes.

查看更多
聊天终结者
5楼-- · 2020-01-29 06:17

__file__ contains the module's location. Use the functions in os.path to extract the directory from it.

查看更多
登录 后发表回答