Full file path in Python

3

I'm using the os.listdir() method to return a list of all files, however the return is just the file name and I'd like it to return the absolute path, does anyone know any way?

The os.path.abspath() method is not working because it is returning my user's folder + the file being that the file is inside my user's subfolders.

    
asked by anonymous 19.05.2014 / 04:32

2 answers

1
___ erkimt ___ Full file path in Python ______ qstntxt ___

I'm using the os.walk('caminho') method to return a list of all files, however the return is just the file name and I'd like it to return the absolute path, does anyone know any way?

The %code% method is not working because it is returning my user's folder + the file being that the file is inside my user's subfolders.

    
______ ___ azszpr16348

I like to use the %code% method. The return is a list of tuples where each tuple is a path with their respective directories and files in the form of lists. The method traverses the current directory and its subdirectories.

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

The %code% method returns a list containing the names of the files and directories found, what might be happening is that you should be using the %code% pointing to the returned list of %code% in the wrong way, applying %code% to each list item should work.

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

The output should look something like this:

%pre%

Update

As an alternative to the method %code% we could be doing something like:

%pre%     
___
19.05.2014 / 22:53
2

The os.listdir() method returns a list containing the names of the files and directories found, what might be happening is that you should be using the os.path.abspath() pointing to the returned list of os.listdir() in the wrong way, applying os.path.abspath() to each list item should work.

import os

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

The output should look 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

Update

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)
    
19.05.2014 / 14:19