ecjb
ecjb

Reputation: 5449

How to get the name of the directory from the name of the directory + the file

In an application, I can get the path to a file which resides in a directory as a string:

"/path/to/the/file.txt"

In order to write another another file into that same directory, I want to change the string "/path/to/the/file.txt" and remove the part "file.txt" to finally only get

"/path/to/the/"

as a string

I could use

string  = "/path/to/the/file.txt"
string.split('/')

and then glue all the term (except the last one) together with a loop

Is there an easy way to do it?

Upvotes: 0

Views: 33

Answers (2)

ecjb
ecjb

Reputation: 5449

Here is what I finally used

    iter = len(string.split('/'))-1

    directory_path_str = ""
    for i in range(0,iter):
        directory_path_str = directory_path_str + srtr.split('/')[i] + "/"

Upvotes: 0

Omer Tekbiyik
Omer Tekbiyik

Reputation: 4744

You can use os.path.basename for getting last part of path and delete it with using replace.

import os
path = "/path/to/the/file.txt"

delete = os.path.basename(os.path.normpath(path))
print(delete) # will return file.txt
#Remove file.txt in path
path = path.replace(delete,'')
print(path)

OUTPUT :

file.txt
/path/to/the/ 

Let say you have an array include txt files . you can get all path like

new_path = ['file2.txt','file3.txt','file4.txt']
for get_new_path in new_path:
    print(path + get_new_path)

OUTPUT :

/path/to/the/file2.txt
/path/to/the/file3.txt
/path/to/the/file4.txt

Upvotes: 1

Related Questions