Monday, May 6, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  27] [ 0]  / answers: 1 / hits: 80098  / 3 Years ago, mon, may 31, 2021, 7:33:47

I am completely new to Linux and Ubuntu.



I have written python code in Windows and want to run it in Ubuntu. It uses a text file for input. The 'path-to-file' in windows looks as follows



c:userdocumentspythonile.txt


How is the location written for Ubuntu?


More From » python

 Answers
1

Rather than hardcoding paths in your Python script we should make use of the path operation from the 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 (/ 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:Usersuserdocumentspython ile.txt ## when running Windows

[#29254] Monday, May 31, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ousear

Total Points: 395
Total Questions: 114
Total Answers: 89

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
ousear questions
Tue, Sep 27, 22, 03:29, 2 Years ago
Thu, Nov 25, 21, 00:51, 3 Years ago
Tue, Feb 22, 22, 17:47, 2 Years ago
;