Python: How to Access Linux Paths - python

Using Python, how does one parse/access files with Linux-specific features, like "~/.mozilla/firefox/*.default"? I've tried this, but it doesn't work.
Thanks

This
import glob, os
glob.glob(os.path.expanduser('~/.mozilla/firefox/*.default'))
will give you a list of all files ending in ".default" in the current user's ~/.mozilla/firefox directory using os.path.expanduser to expand the ~ in the path and glob.glob to match the *.default file pattern.

~ is expanded by the shell and not a real path. As such you have to navigate there manually.
import os
homeDir = os.environ['HOME']
f = open( homeDir + '/.mozilla/firefox/*.default' )
# ...

It's important to remember:
use of the tilde ~ expands the home directory as per Poke's answer
use of the forward slash / is the separator for linux / *nix directories
by default, *nix systems such as linux for example has a wild card globbing in the shell, for instance echo *.* will return back all files that match the asterisk dot asterisk (as per Will McCutcheon's answer!)

http://docs.python.org/library/os.html
Gives a complete reference if you would like to change directory or give paths.
You can for example give relative paths and access specific files.
If you would like to execute commands then http://docs.python.org/library/commands.html provides nice wrappers for the os.popen() function

Related

Python open a file in a subdirectory - linux

Is it possible to open a file for reading in a sub directory without having to use os.listdir()? Something like this maybe?
f1 = open('/SCRIPT/PYTHON/monomer-b/{}'.format(xyzfile)).read()
I am running the python script in /SCRIPT/PYTHON the files that I want to call is in /SCRIPT/PYTHON/monor-b. Any suggestions
You can use relative paths while opening files in python:
import os
file_content = open(os.path.join('./monomer-b', xyzfile)).read()
Also, by default all paths looks up starting at current directory, so the './' part of subdir name is not necessary. Using os.path.join is better practice than string concatenation or formatting, because it use correct path separators and another OS-specific things.

have two variables to be joined as a path using python

Hi i have two variables to be joined as a path,
SUITE_DIR = D:/Squish and
SUITE_NAME = HMI_Remote
Now i want DIR_name as D:/Squish/HMI_Remote
when i tried
os.path.join(SUITE_DIR,SUITE_NAME)
it gave me D:/Squish\HMI_Remote
why is it so and how get it right ?
thanks in advance
Brijesh
In os.path there is a function normpath, which gets the input straight (and resolves relative parts and some further improvements).
os.path.join uses the separator of the OS, which in the case of Windows, is \. Windows can use either \ or / though.
Just change SUITE_DIR to be SUITE_DIR = 'D:\Squish' and you'll be fine.
It looks you're running this python script under Windows and the path separator for Windows is \ and not /.
You should have instead created the string SUITE_DIR using os.sep

What is 'subdir' defined var in python 3 for all OS?

I have a script in Python which i get 3 arguments from the user
One of the arguments is a folder path in which there are some files i need to use
Since my program is designed for all OS, i would like to know how to use the path from the argument correctly to get to my required files
I.E.
if i get the following path :
c:\windows
i would like to be able to get 1.exe in this folder,
In windows it will be slash or backslash but in unix systems it will be probably different,
As i understand there is a const or defined var from 'os' module in which i can use as this subdir sign, where can i find it ?
Thank you
Just use os.path.join and Python will take care of the slash for you:
path = os.path.join(sys.argv[1], '1.exe')
The platform-specific path separator is stored as os.sep.
Use os.path.join(). For example:
os.path.join(dirname, "1.exe")

os.makedirs doesn't understand "~" in my path

I have a little problem with ~ in my paths.
This code example creates some directories called ~/some_dir and do not understand that I wanted to create some_dir in my home directory.
my_dir = "~/some_dir"
if not os.path.exists(my_dir):
os.makedirs(my_dir)
Note this is on a Linux-based system.
You need to expand the tilde manually:
my_dir = os.path.expanduser('~/some_dir')
The conversion of ~/some_dir to $HOME/some_dir is called tilde expansion and is a common user interface feature. The file system does not know anything about it.
In Python, this feature is implemented by os.path.expanduser:
my_dir = os.path.expanduser("~/some_dir")
That's probably because Python is not Bash and doesn't follow same conventions. You may use this:
homedir = os.path.expanduser('~')

How can I find path to given file?

I have a file, for example "something.exe" and I want to find path to this file
How can I do this in python?
Perhaps os.path.abspath() would do it:
import os
print os.path.abspath("something.exe")
If your something.exe is not in the current directory, you can pass any relative path and abspath() will resolve it.
use os.path.abspath to get a normalized absolutized version of the pathname
use os.walk to get it's location
import os
exe = 'something.exe'
#if the exe just in current dir
print os.path.abspath(exe)
# output
# D:\python\note\something.exe
#if we need find it first
for root, dirs, files in os.walk(r'D:\python'):
for name in files:
if name == exe:
print os.path.abspath(os.path.join(root, name))
# output
# D:\python\note\something.exe
if you absolutely do not know where it is, the only way is to find it starting from root c:\
import os
for r,d,f in os.walk("c:\\"):
for files in f:
if files == "something.exe":
print os.path.join(r,files)
else, if you know that there are only few places you store you exe, like your system32, then start finding it from there. you can also make use of os.environ["PATH"] if you always put your .exe in one of those directories in your PATH variable.
for p in os.environ["PATH"].split(";"):
for r,d,f in os.walk(p):
for files in f:
if files == "something.exe":
print os.path.join(r,files)
Just to mention, another option to achieve this task could be the subprocess module, to help us execute a command in terminal, like this:
import subprocess
command = "find"
directory = "/Possible/path/"
flag = "-iname"
file = "something.foo"
args = [command, directory, flag, file]
process = subprocess.run(args, stdout=subprocess.PIPE)
path = process.stdout.decode().strip("\n")
print(path)
With this we emulate passing the following command to the Terminal:
find /Posible/path -iname "something.foo".
After that, given that the attribute stdout is binary string, we need to decode it, and remove the trailing "\n" character.
I tested it with the %timeit magic in spyder, and the performance is 0.3 seconds slower than the os.walk() option.
I noted that you are in Windows, so you may search for a command that behaves similar to find in Unix.
Finally, if you have several files with the same name in different directories, the resulting string will contain all of them. In consequence, you need to deal with that appropriately, maybe using regular expressions.
This is really old thread, but might be useful to someone who stumbles across this. In python 3, there is a module called "glob" which takes "egrep" style search strings and returns system appropriate pathing (i.e. Unix\Linux and Windows).
https://docs.python.org/3/library/glob.html
Example usage would be:
results = glob.glob('./**/FILE_NAME')
Then you get a list of matches in the result variable.
Uh... This question is a bit unclear.
What do you mean "have"? Do you have the name of the file? Have you opened it? Is it a file object? Is it a file descriptor? What???
If it's a name, what do you mean with "find"? Do you want to search for the file in a bunch of directories? Or do you know which directory it's in?
If it is a file object, then you must have opened it, reasonably, and then you know the path already, although you can get the filename from fileob.name too.

Categories

Resources