1

I am trying to access a path starting with ~/ in linux using python and its not working. Tried getting absolute path but that also is failing for ~/paths. What is the right way to handle ~/path in python?

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

Results:

test.txt

python3

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

Results in,

False
False
test.txt
0
Jerin Antony
  • 133
  • 1
  • 9

1 Answers1

0

An easier way in Python 3, is with the builtin pathlib module:

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
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53