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?
Asked
Active
Viewed 95 times
3 Answers
2
-
The os module worked! Thank you! (Also, to find the current directory, you can use os.getcwd) – D4rkM4sterBR Apr 14 '16 at 18:19
-
1@D4rkM4sterBR, I edited the answer to avoid confusing the script directory with the process current directory. You do not want `os.getcwd`. See the linked question. – Eryk Sun Apr 14 '16 at 18:21
-
I found out you can split the os.getcwd string into a list, reverse it, delete the last item (which would be the current folder), reverse it again, join it, and you will get the upper folder. It also works. – D4rkM4sterBR Apr 14 '16 at 18:33
-
Well I'm not really for using `os.getcwd`. If you're doing that regardless, you can use `list.pop(0)` (where list is your list obtained by the original split) to remove the first item of the list. – Malcolm Apr 14 '16 at 18:41
-
@D4rkM4sterBR, you said "generate a folder in a directory that was above the program's location". `os.getcwd` is completely unrelated to this requirement. The current working directory can be *anything* depending on the working directory of the parent process (e.g. cmd.exe or explorer.exe) or a directory passed explicitly to [`CreateProcess`](https://msdn.microsoft.com/en-us/library/ms682425) as `lpCurrentDirectory`. – Eryk Sun Apr 14 '16 at 18:59
0
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.

Community
- 1
- 1

PistolPete
- 46
- 6
-
I don't quite get it, but I'm going to look into it. I didn't even know this library existed! Thanks! – D4rkM4sterBR Apr 14 '16 at 18:11
0
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)

chickity china chinese chicken
- 7,709
- 2
- 20
- 49