Passing a file location to python
Rather than hardcoding paths in your Python script we should make use of the path operation from module OS
os.path.expanduser(path) expands the path to the user’s home directory
os.path.join(path1,*path2*,…) joins path elements with the appropriate separator
os.sep gives the OS dependent path separator (
os.getcwd() gives the current working directory
os.path.abspath(path) gives the OS dependent absolute path of a given path
os.path.join(path1,*path2*,…) joins path elements with the appropriate separator
os.sep gives the OS dependent path separator (
/
for Linux/Unix, \
for Windows)os.getcwd() gives the current working directory
os.path.abspath(path) gives the OS dependent absolute path of a given path
Example:
>>>import os
>>>path = os.path.join(os.path.expanduser('~'), 'documents', 'python', 'file.txt')
>>>print (path)
Result
/home/user/documents/python/file.txt ## when on Ubuntu
C:\Users\user\documents\python\file.txt ## when running on Windows
Source link: https://askubuntu.com/users/3940/takkat
Comments
Post a Comment