Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a file one directory up?

Tags:

python

io

How can I create a file in python one directory up, without using the full path?

I would like a way that worked both for windows and linux.

Thanks.

like image 255
nunos Avatar asked Oct 22 '09 14:10

nunos


People also ask

Does mkdir create file?

New! Save questions or answers and organize your favorite content. Learn more.

How do I return a file path?

Starting with “/” returns to the root directory and starts there. Starting with “../” moves one directory backwards and starts there. Starting with “../../” moves two directories backwards and starts there (and so on…) To move forward, just start with the first subdirectory and keep moving forward.


2 Answers

Use os.pardir (which is probably always "..")

import os
fobj = open(os.path.join(os.pardir, "filename"), "w")
like image 110
u0b34a0f6ae Avatar answered Sep 29 '22 13:09

u0b34a0f6ae


People don't seem to realize this, but Python is happy to accept forward slash even on Windows. This works fine on all platforms:

fobj = open("../filename", "w")
like image 27
Ned Batchelder Avatar answered Sep 29 '22 14:09

Ned Batchelder