What is the Python equivalent of Perl's FindBin? [duplicate] - python

This question already has answers here:
How do you properly determine the current script directory?
(16 answers)
Closed 5 years ago.
In Perl, the FindBin module is used to locate the directory of the original script. What's the canonical way to get this directory in Python?
Some of the options I've seen:
os.path.dirname(os.path.realpath(sys.argv[0]))
os.path.abspath(os.path.dirname(sys.argv[0]))
os.path.abspath(os.path.dirname(__file__))

You can try this:
import os
bindir = os.path.abspath(os.path.dirname(__file__))
That will give you the absolute path of the current file's directory.

I don't use Python very often so I do not know if there is package like FindBin but
import os
import sys
bindir = os.path.abspath(os.path.dirname(sys.argv[0]))
should work.

To update on the previous answers, with Python 3.4+, you can now do:
import pathlib
bindir = pathlib.Path(__file__).resolve().parent
Which will give you the same, except you'll get a Path object that is way more nice to work with.

Related

How to load an icon using relative path in python [duplicate]

This question already has answers here:
Using QIcon does not display the image
(2 answers)
Closed 1 year ago.
I created a package that contains an icon.png inside a resource-folder:
../mypackage/resource/icon.png
../mypackage/qtprogram.py
I am now trying to access the icon.png in qtprogram.py. As they are both in mypackage directory, I tried using:
QtGui.QIcon("resource//icon.png")
but it did not work. However, using the full path (in relation to the main script path) did. Since this should be a shareable package, I would like to avoid using the full path. How can I do this?
I think it should be \\ (or) r'relative-path-to-file' instead of // in QtGui.QIcon("resource//icon.png").
I would use the os library.
import os
# If you plan to use to without PyInstaller
icon_path = os.path.join(os.path.dirname(__file__), r'resources\icon.png')
# If you plan to use to pyinstaller
icon_path = os.path.join(os.path.abspath(os.getcwd()), r'resources\icon.png')

List the content of a folder using python [duplicate]

This question already has answers here:
How can I list the contents of a directory in Python?
(8 answers)
Closed 4 years ago.
Is it possible to output the contents of a folder in python ?
If, say you had a function and you would pass the folder path to its argument?
What would be the simplest way for a beginner to take?
By "simplest" I mean, without using any modules.
Note
Google usually leads me to stackoverflow. Plus I am not looking for generic answers. I am looking for insight based on experience and wit, which I can only find here.
You could use os.listdir() to look at the contents of a directory. It takes the path as an argument, for example:
import os
directory = os.listdir('/')
for filename in directory:
print(filename)
prints this for me:
bin
home
usr
sbin
proc
tmp
dev
media
srv
etc
lib64
mnt
boot
run
var
sys
lib
opt
root
.dockerenv
run_dir
How about listdir? Let's try like this way-
import os
def ShowDirectory:
return os.listdir("folder/path/goes/here")
ShowDirectory()
With function.
def ListFolder(folder):
import os
files = os.listdir(folder)
print(*files,sep="\n")
Please use google first next time...it seems you are looking for this:
How can I list the contents of a directory in Python?
The accepted answer there:
import os
os.listdir("path") # returns list

Python check if a directory exists, then create it if necessary and save graph to new directory? [duplicate]

This question already has answers here:
How can I safely create a directory (possibly including intermediate directories)?
(28 answers)
Closed 5 years ago.
so I want this to be independent of the computer the code is used on, so I want to be able to create a directory in the current directory and save my plots to that new file. I looked at some other questions and tried this (I have two attempts, one commented out):
import os
from os import path
#trying to make shift_graphs directory if it does not already exist:
if not os.path.exists('shift_graphs'):
os.mkdirs('shift_graphs')
plt.title('Shift by position on '+str(detector_num)+'-Detector')
#saving figure to shift_graphs directory
plt.savefig(os.path.join('shift_graphs','shift by position on '+str(detector_num)+'-detector'))
print "plot 5 done"
plt.clf
I get the error :
AttributeError: 'module' object has no attribute 'mkdirs'
I also want to know if my idea of saving it in the directory will work, which I haven't been able to test because of the errors I've been getting in the above portion.
os.mkdirs() is not a method in os module.
if you are making only one direcory then use os.mkdir() and if there are multiple directories try using os.makedirs()
Check Documentation
You are looking for either:
os.mkdir
Or os.makedirs
https://docs.python.org/2/library/os.html
os.makedirs makes all the directories, so if I type in shell (and get nothing):
$ ls
$ python
>>> import os
>>> os.listdir(os.getcwd())
[]
>>> os.makedirs('alex/is/making/a/path')
>>> os.listdir(os.getcwd())
['alex']
It has made all the directories and subdirectories. os.mkdir would throw me an error, because there is no "alex/is/making/a" directory.

How to change file extension with Python? [duplicate]

This question already has answers here:
Extracting extension from filename in Python
(33 answers)
Closed 7 years ago.
I'm trying to make a program that will take a file, say my_test_file.log and make a new file called my_test_file.mdn. I'd like to be able to use this program by typing python renameprogram.py my_test_file.log into the command line. The original file will always end in .log.
from shutil import copyfile
from glob import glob
map(lambda x:copyfile(x,x[:-3]+"mdn"),glob("*.log"))
or perhaps more simply
...
import sys
copyfile(sys.argv[1],sys.argv[1][:-3]+"mdn")
You certainly can create a Python program that will accomplish this, but there are shell level commands that already do this.
For Linux/Unix:
mv my_test_file.log my_test_file.mdn
For Windows (see this link):
rename my_test_file.log my_test_file.mdn

Copy directory contents into a directory with python [duplicate]

This question already has answers here:
How do I copy an entire directory of files into an existing directory using Python?
(15 answers)
Closed 4 years ago.
I have a directory /a/b/c that has files and subdirectories.
I need to copy the /a/b/c/* in the /x/y/z directory. What python methods can I use?
I tried shutil.copytree("a/b/c", "/x/y/z"), but python tries to create /x/y/z and raises an error "Directory exists".
I found this code working which is part of the standard library:
from distutils.dir_util import copy_tree
# copy subdirectory example
from_directory = "/a/b/c"
to_directory = "/x/y/z"
copy_tree(from_directory, to_directory)
Reference:
Python 2: https://docs.python.org/2/distutils/apiref.html#distutils.dir_util.copy_tree
Python 3: https://docs.python.org/3/distutils/apiref.html#distutils.dir_util.copy_tree
You can also use glob2 to recursively collect all paths (using ** subfolders wildcard) and then use shutil.copyfile, saving the paths
glob2 link: https://code.activestate.com/pypm/glob2/
from subprocess import call
def cp_dir(source, target):
call(['cp', '-a', source, target]) # Linux
cp_dir('/a/b/c/', '/x/y/z/')
It works for me. Basically, it executes shell command cp.
The python libs are obsolete with this function. I've done one that works correctly:
import os
import shutil
def copydirectorykut(src, dst):
os.chdir(dst)
list=os.listdir(src)
nom= src+'.txt'
fitx= open(nom, 'w')
for item in list:
fitx.write("%s\n" % item)
fitx.close()
f = open(nom,'r')
for line in f.readlines():
if "." in line:
shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
else:
if not os.path.exists(dst+'/'+line[:-1]):
os.makedirs(dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
f.close()
os.remove(nom)
os.chdir('..')

Categories