【问题标题】:Why subprocess.call('ls ~/mnt', shell=True) works but os.path.exists('~/mnt') doesn't? [duplicate]为什么 subprocess.call(\'ls ~/mnt\', shell=True) 有效,但 os.path.exists(\'~/mnt\') 无效? [复制]
【发布时间】:2022-08-17 00:37:04
【问题描述】:

我正在尝试使用 python 在 linux 中访问以 ~/ 开头的路径,但它不起作用。尝试获取绝对路径,但这对于 ~/paths 也是失败的。在 python 中处理 ~/path 的正确方法是什么?

mkdir ~/mnt
touch ~/mnt/test.txt
ls ~/mnt

结果:

test.txt

蟒蛇3

import os
import subprocess
print(os.path.exists(\'~/mnt\'))
print(os.path.exists(os.path.abspath(\'~/mnt\')))
subprocess.call(\'ls ~/mnt3\', shell=True)

结果是,

False
False
test.txt
0

标签: python


【解决方案1】:

Python 3 中更简单的方法是使用内置的 pathlib 模块:

from pathlib import Path

# don't forget the `expanduser()` here
p = Path('~/.mnt').expanduser()

print(p.exists())  # true
print(p.absolute().exists())  # true

p2 = p / 'other_file'
print(str(p2))  # /Users/<user>/.mnt/other_file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-10
    • 2013-06-15
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 2016-10-03
    • 2016-09-18
    • 2020-06-17
    相关资源
    最近更新 更多