1

how could do print the path directory of my file saved with python. For ad example, i start with idle3 (Fedora 24), i save the IDLE code on: /home/jetson/Desktop/Python/Programs and in the code is written:

f = open("Hello.txt","w")
f.write("This is a test","\n")
f.close()

My question is: after f.close i would print the directory grabbed with

import sys.os 

print("The file is saved in ",direcotrysaved)

It's possible?

1
  • @SSNR That gives the path to current .py file, which does not have to be where open will open the file. Commented Oct 1, 2016 at 8:25

4 Answers 4

3

Convert the relative path to absolute path:

path = os.path.abspath(filename)

Then take just the directory from the absolute path:

directory = os.path.dirname(path)

That will work regardless of what filename is. It could by just a filename, a relative path or absolute path.

See os.path documentation for other useful functions.

Sign up to request clarification or add additional context in comments.

Comments

0

If no path is given then the file is opened in the current working directory. This is returned by os.getcwd().

Comments

0

You can use os.getcwd() for getting the current working directory:

import os

os.getcwd()

Otherwise, you could also specify the full path for the file when opening it, e.g.

f.open('/path/to/the/folder/Hello.txt', 'w')

Comments

0

Using f.name provides the file name if you didn't supply it as a separate variable.
Using os.path.abspath() provides the full file name including it's directory path i.e. in this case "/home/rolf/def"
Using os.path.dirname() strips the file name from the path, as that you already know.

>>> import os
>>> f=open('xxxx.txt','w')
>>> f.close()
>>> print(f.name,'Stored in', os.path.dirname(os.path.abspath(f.name)))

xxxx.txt Stored in /home/rolf/def

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.