Full Python file path

Asked

Viewed 8,851 times

3

I’m using the method os.listdir() to return a list of all the files, however the return is only the file name and I would like it to return the absolute path, someone knows some way ?

The method os.path.abspath() is not working as it is returning me my user’s folder + the file being that the file is within my user’s subfolders.

  • I solved my problem using the string I used in the listdir() + method, but still, it would be good to know what the problem of the os.path.abspath method is.()

4 answers

2

The method os.listdir() returns a list containing the names of the found files and directories, what may be happening is that you must be using the method os.path.abspath() pointing to the returned list of os.listdir() wrongly, by applying os.path.abspath() for each item on the list should work.

import os

dirlist = os.listdir(".") 
for i in dirlist:
    filename = os.path.abspath(i)
    print(filename)

The exit must be something like this:

/home/user/dir1/dir2/arquivo1.py
/home/user/dir1/dir2/arquivo2.py
/home/user/dir1/dir2/foobarDir1
/home/user/dir1/dir2/foobarDir2

Updating

As an alternative to the method os.walk() we could be doing something like:

import os

filedirlist = os.listdir(".") 
filelist = [os.path.abspath(f) for f in filedirlist if os.path.isfile(f)]
dirlist  = [os.path.abspath(d) for d in filedirlist if os.path.isdir(d)]

# Lista de arquivos com path completo.
for i in filelist:
    print(i)

# Lista de diretórios com path completo.
for i in dirlist:
    print(i)

2


I like to use the method os.walk('caminho'). The return is a list of tuples. Where each tuple represents a path with its respective directories and files in the form of lists. The method runs through the current directory and its subdirectories.

import os
for caminho, diretorios, arquivos in os.walk():
    print caminho
    print diretorios
    print arquivos

0

Another interesting way to resolve this issue is by using the following code:

from os import chdir, listdir
from os.path import isfile

cam = input('Digite o caminho: ')

chdir(cam)

soma = 0
for c in listdir():
    if isfile(c):
        print(cam + '\\' + c)
        soma += 1
print()
print(f'{soma} arquivos encontrados.')

Note that this code gets the path from a directory (folder), from which will be listed all the files along with their absolute paths.

0

I usually use the os.walk()as follows:

from os import walk

for caminho,_,arquivo in walk('.'):
   print(str(caminho)+"/"+str(arquivo))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.