Passing a file location to python

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:user\documents\python\file.txt

How is the location written for Ubuntu?


Solution 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:\Users\user\documents\python\file.txt ## when running Windows

Solution 2:

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

Solution 3:

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:

~/