Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I am complete newbie on linux and ubuntu. So my apologies for the dumb question. I have written python code in windows and want to run it in ubuntu, it uses an text file for input. the 'path-to-file' in windows looks as follows c:user\documents\python\file.txt, how is the location written for ubuntu?

share|improve this question

3 Answers 3

up vote 4 down vote accepted

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:\Users\user\documents\python\file.txt ## when running Windows
share|improve this answer
    
Thank you. This answer is going to help me a lot –  Jaffels Oct 1 '13 at 10:42

I don't have permission to add comments...so I will just try to answer.

The path at UNIX will be like: /home/user/file.txt

When you at any folder and want to get the absolute path of a file, you could use the readlink command:

readlink -f file.txt

example at our server:

$ readlink -f format.log 
/home/dli/format.log
share|improve this answer

File paths are written as-

/path/to/file

Everything in your home folder is located inside /home/username/

So, if you have a file on your desktop, it is located in /home/username/Desktop/

Other partitions are mounted in /media by default.

If you directly want to get the path of a file, you can copy the file, and paste it into your text editor, this should give you the path to your file. Put a \ before every space in the path to 'escape' the space. e.g. "/media/myuseraccount/Desktop/an awesome file" would be written as -

/media/myuseraccount/Desktop/an\ awesome\ file

Another thing to note is that in Linux, your file names are case sensitive, so 'desktop' is not the same as 'Desktop'.

Finally, a shortcut to your home folder is to type ~

So, you can access your desktop by typing -

~/Desktop

and you can access your home folder by typing -

~/
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.