I'm using python 2.x and I don't know how to make my script randomly choose directories in the same PC to copy files. It's quite important because it is for my final project.Any help is appreciated.
You should have a look at tempfile package
In [1]: import tempfile
In [2]: print([f for f in dir(tempfile) if not f.startswith('_')])
['NamedTemporaryFile', 'SpooledTemporaryFile', 'TMP_MAX', 'TemporaryFile', 'gettempdir', 'gettempprefix', 'mkdtemp', 'mkstemp', 'mktemp', 'tempdir', 'template']
In [3]: help(tempfile.mkdtemp)
Help on function mkdtemp in module tempfile:
mkdtemp(suffix='', prefix='tmp', dir=None)
User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
The directory is readable, writable, and searchable only by the
creating user.
Caller is responsible for deleting the directory when done with it.
Related
I'm trying to validate if a directory received as user input exists using the os module
This is how I'm accepting the input:
directory = input("Hi ! \n please type a directory, thanks !")
The idea is that I want to make sure the user will type an existing directory and nothing else
from pathlib import Path
def is_valid_directory(filename):
p = Path(filename)
return p.exists() and p.is_dir()
pathlib is an enormously convenient module for working with file paths of any sort. The p.exists() call is redundant since p.is_dir() returns False for nonexistent paths, but checking both would allow you to e.g. give better error messages.
EDIT: Note that pathlib was added in Python 3.4. If you're still using an old version for whatever reason, you can use the older os.path.isdir(filename) function.
Have you read the docs for the os module?
Check out the following two links:
os.path.exists()
Return True if path refers to an existing path.
os.path.isdir()
Return True if path is an existing directory.
In essence, I'm trying to make an extension system, where each plugin hooks into the important functions via the respective function in the file. I need a way to run this function and get the return value, by just looping through the "plugins" directory.
Any way I could do this?
you can import files dinamicaly using __import__
so you just need to iterate the folder looking for py files (not pyc) and import them
for root, dirs, files in os.walk(src_path):
for f in files:
if f.endswith('.py'):
m = __import__(f)
m will now be the instanc of the module , so if you have a function called my_func under it, you can do:
m.my_func()
or if you have the name of the function as string:
getattr(m,'my_func')()
Let's say that I have a folder, x, containing the two folders foo and bar. Inside foo I have a Python script and inside bar, I have my data (let's say a couple of .txt files). Now, from within my script, I would like to access my data. I could simply use this command and call it a day:
fileList = glob.glob('/absolute/path/to/bar/*.txt')
However, using this method, my script would break if I moved my x folder.
What's the easiest way to specify the path in a relative manner that allows me to move around the parent folder, x, freely?
../ specifies your parent directory, so ../bar/*.txt.
Like John Gordon said, this works assuming you're inside x/foo/ and running the script from there.
If you're not executing the script from its own directory, you'll need to find out where your script currently is. This is not trivial. felipsmartins' solution of using os.path.dirname(os.path.dirname(__file__)) is generally fine, but doesn't work in all cases. See e.g. here: How to properly determine current script directory in Python?
I think __file__ is a nice approach:
import glob
import os
# "x" folder
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
files = glob.glob(os.path.join(base_dir, 'bar', '*.txt'))
Working from top directory is a lot easier. Django and other frameworks does it too.
Also, it solves issues when invoking script from command line and from different locations.
Another approch is usging os.chdir(), changing working directory:
import glob
import os
# same that: cd /absolute path/for/x folder
os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
files = glob.glob(os.path.join('bar', '*.txt'))
Zend Framework (PHP) uses the above approach in bootstrap file.
Both solutions works very well for all cases.
I've been working on a project that creates its own .py files that store handlers for the method, I've been trying to figure out how to store the Python files in folder and open them. Here is the code I'm using to create the files if they don't already exist, then importing the file:
if os.path.isfile("Btn"+ str(self.ButtonSet[self.IntBtnID].IntPID) +".py") == False:
TestPy = open("Btn"+ str(self.ButtonSet[self.IntBtnID].IntPID) +".py","w+")
try:
TestPy.write(StrHandler)
except Exception as Error:
print(Error)
TestPy.close()
self.ButtonSet[self.IntBtnID].ImpHandler = __import__("Btn" + str(self.IntBtnID))
self.IntBtnID += 1
when I change this line:
self.ButtonSet[self.IntBtnID].ImpHandler = __import__("Btn" + str(self.IntBtnID))
to this:
self.ButtonSet[self.IntBtnID].ImpHandler = __import__("Buttons\\Btn" + str(self.IntBtnID))
the fill can't be found and ends up throwing an error because it can't find the file in the folder.
Do know why it doesn't work I just don't know how to get around the issue:/
My question is how do I open the .py when its stored in a folder?
There are a couple of unidiomatic things in your code that may be the cause of your issue. First of all, it is generally better to use the functions in os.path to manipulate paths to files. From your backslash usage, it appears you're working on Windows, but the os.path module ensures consistent behaviour across all platforms.
Also there is importlib.import_module, which is usually recommended over __import__. Furthermore, in case you want to load the generated module more than once during the lifetime of your program, you have to do that explicitly using imp.reload.
One last tip: I'd factor out the module path to avoid having to change it in more than one place.
You can't reference a path directory when you are importing files. Instead, you want to add the directory to your path and then import the name of the module.
import sys
sys.path.append( "Buttons" )
__import__("Btn"+str(self.IntBtnId))
See this so question for more information.
The first argument to the __import__() function is the name of the module, not a path to it. Therefore I think you need to use:
self.ButtonSet[self.IntBtnID].ImpHandler = __import__("Buttons.Btn" + str(self.IntBtnID))
You may also need to put an empty __init__.py file in the Buttons folder to indicate it's a package of modules.
Currently if I want to specify and create a new directory, I'll do:
newPath = os.path.join(oldPath,"newfolder")
if(not os.path.exists(newPath)): os.makedirs(newPath)
I'm wondering if a pre-packaged os function (or in other package) exists to do this in one function? I know I can make my own but I'd rather a pre-packaged solution.
Try pylib's path functionality.
It's basically a really nice OOP (Object Oriented) abstraction around local paths (and svn paths).
Example:
from py.path import local
p = local("/some/path").join("/some/other/path").mkdir("/some/oth/path")
NB: The above example is contrived. Please refer to the documentation.