Making a directory for a file - python

I was making a exercise generator algorithm for my friend, but I stumbled across a problem. It is a python program, and I wanted to generate a folder in a directory that was above the program's location (like, the python file is in 'C:\Documents\foo' and the folder should be created in 'C:\Documents') so that it could then store the file the program created. Is there a way to do this or should I try something else?

Use the path argument of the os.mkdir() function.
Getting the current script directory is not a built-in feature, but there are multiple hacks suggested here.
Once you get the current script directory, you can build a path based off of that.

Not super familiar with Python in a Windows environment, but this should be easily do-able. Here is a similar question that might be worth looking at: How to check if a directory exists and create it if necessary?
Looks like the pathlib module might do what you are looking for.
from pathlib import Path
path = Path("/my/directory/filename.txt")
try:
if not path.parent.exists():
path.parent.mkdir(parents=True)
except OSError:
# handle error; you can also catch specific errors like
# FileExistsError and so on.

Appears to work on Win 7 with Python 2.7.8 as described:
import os.path
createDir = '\\'.join((os.path.abspath(os.path.join(os.getcwd(), os.pardir)), 'Foo'))
if not os.path.exists(createDir):
os.makedirs(createDir)

Related

Python Calling Function from Another File

I am using Python 2.7 on Windows 7 Professional.
I am trying to call a function saved in another file to run in this file's code.
Function called dosomething is found in anotherfile.py
anotherfile.py is in the same directory as current code.
My call in this file is simple:
import anotherfile
print anotherfile.dosomething
I am getting an error: No module named anotherfile
The problem is the same as I found in this post
I don't understand the solution but I'd like any insight?
Thank you.
EDIT: The other question/answers discuss resetting CLASSPATH and setting PYTHONPATH. I explored this but was not sure how to do this. Perhaps relevant?
Let us have two files in the same directory. Files are called main.py and another.py.
First write a method in another.py:
def do_something():
return "This is the do something method"
Then call the method from main.py. Here is the main.py:
import another
print another.do_something()
Run main.py and you will get output like this:
This is the do something method
N.B.: The above code is being executed using Python 2.7 in Windows 10.
Specify the module then the file then the import like so:
from this_module.anotherfile import dosomething
or if you want all functions from "anotherfile.py"
from this_module.anotherfile import *
and then you can call the "dosomething" command without the "anotherfile" prefix.
I ran into same problem. After ample of trials, I ended up solving it with the below mentioned solution:
Make sure your current file and anotherfile.py lies in same location of system path.
Say your another.py and current file lies at location : "C:/Users/ABC"
In case, one is not aware of system path. Use below code in current file:
import sys
print(sys.path)
import sys
sys.path.append('/C:/Users/ABC/')
Then you do below code in same current code:
from another import dosomething
I found the issue. Python was looking in another directory for the files. I explicitly set my working directory as the path to where thisfile.py and anotherfile.py reside and it works. Thank you for all the quick replies.

Making Python guess a file Name

I have the following function:
unpack_binaryfunction('third-party/jdk-6u29-linux-i586.bin' , ('/home/user/%s/third-party' % installdir), 'jdk1.6.0_29')
Which uses os.sys to execute a java deployment. The line, combined with the function (Which is unimportant, it just calls some linux statements) works perfectly.
However, this only works if in the 'third-party' folder is specificaly that version of the jdk.
Therefore I need a code that will look at the files in the 'third-party' folder and find one that starts with 'jdk' and fill out the rest of the filename itself.
I am absolutely stuck. Are there any functions or libraries that can help with file searching etc?
To clarify: I need the code to not include the entire: jdk-6u29-linux-i586.bin but to use the jdk-xxxx... that will be in the third-party folder.
This can easily be done using the glob module, and then a bit a string parsing to extract the version.
import glob
import os.path
for path in glob.glob('third-party/jdk-*'):
parent, name = os.path.split(path) # "third-party", "jdk-6u29-linux-i586.bin"
version, update = name.split('-')[1].split('u') # ("6", "29")
unpack_binaryfunction(path, ('/home/user/%s/third-party' % installdir), 'jdk1.{}.0_{}'.format(version, update))

Python function that navigates to top level module directory

I'm trying to write a function in python that navigates to the top level directory of the project i'm working on for bookkeeping purposes. Instead of writing abs paths everywhere which may change depending on the machine, I think this would be easier.
However, my funct isn't super sophisticated and goes into inf loops in situations. Does anyone have a good strategy for something like this?
def chdir_top():
while os.getcwd().split('/')[-1] != "myproj":
os.chdir('..')
if os.getcwd().split('/')[-2] != "myproj" and
"myproj" in os.listdir(os.getcwd()):
os.chdir("myproj")
Thank you.
Do not use os.getcwd() for this; use the module-level __file__ name instead. If the current working directory is elsewhere, you end up in an infinite loop when you reach the root directory and continually fail to go up one directory.
import os.path
here = os.path.dirname(os.path.abspath(__file__))
Now here is a path to the directory containing the current Python file. Use that to find the top of your project (not by using chdir() but by using os.path functions).

Simplest way to Import a shared python script relative to the current script

I am trying to import one python script from another. I have a few common functions defined in one script and then lots of other scripts that want to import those functions. No classes, just functions.
The importing script needs to import from a relative path e.g. ../../SharedScripts/python/common.py
I then a have a few functions def f1(...) defined which I will call.
I found the imp module which seemed to be the right thing to use but I was unable to figure out the exact syntax that would work for my example.
Can someone suggest the correct code to use or the simplest approach if imp is not the right module?
SOLUTION from the answers below I was able to get this working...
projectKey = 'THOR'
# load the shared script relative to this script
sys.path.append(os.path.dirname(__file__) + '/../../SharedScripts/python')
import jira
jira.CheckJiraCommitMessage(sys.argv[1], sys.argv[2], projectKey)
Where I had an empty __init__.py and a jira.py in the SharedScripts/python directory with plain function definitions.
Why not adding ../../SharedScripts/python/ to the python path? Then you could use common.py like any other module:
import common
common.f1()
You can alternate the Python path through the system variable PYTHONPATH or by manipulating it directly from python: sys.path.append("../../SharedScripts/python/")
Please notice that it is probably wiser to work with absolute pathes... (The current directory of the app could change)
To get the absolute path could can call use the function os.path.abspath: os.path.abspath('../../SharedScripts/python/')
A possible way is to add the directory to the Python path before doing the import.
#!/usr/bin/env python
import sys
sys.path.append('../../SharedScripts/python')
import common

How do I use a relative path in a Python module when the CWD has changed?

I have a Python module which uses some resources in a subdirectory of the module directory. After searching around on stack overflow and finding related answers, I managed to direct the module to the resources by using something like
import os
os.path.join(os.path.dirname(__file__), 'fonts/myfont.ttf')
This works fine when I call the module from elsewhere, but it breaks when I call the module after changing the current working directory. The problem is that the contents of __file__ are a relative path, which doesn't take into account the fact that I changed the directory:
>>> mymodule.__file__
'mymodule/__init__.pyc'
>>> os.chdir('..')
>>> mymodule.__file__
'mymodule/__init__.pyc'
How can I encode the absolute path in __file__, or barring that, how can I access my resources in the module no matter what the current working directory is? Thanks!
Store the absolute path to the module directory at the very beginning of the module:
package_directory = os.path.dirname(os.path.abspath(__file__))
Afterwards, load your resources based on this package_directory:
font_file = os.path.join(package_directory, 'fonts', 'myfont.ttf')
And after all, do not modify of process-wide resources like the current working directory. There is never a real need to change the working directory in a well-written program, consequently avoid os.chdir().
Building on lunaryorn's answer, I keep a function at the top of my modules in which I have to build multiple paths. This saves me repeated typing of joins.
def package_path(*paths, package_directory=os.path.dirname(os.path.abspath(__file__))):
return os.path.join(package_directory, *paths)
To build the path, call it like this:
font_file = package_path('fonts', 'myfont.ttf')
Or if you just need the package directory:
package_directory = package_path()

Categories

Resources