Get the number of files contained in a directory

Asked

Viewed 61 times

0

I’m using the following script:

import os
ler = os.system('ls livros | wc -l')
print(ler)

The goal was the variable ler receive the number of existing files inside a directory but it always gets the value 0 even if there are files in the directory.

2 answers

2


The standard bibilioteca os provides a very complete and portable interface of access to the operating system file system.

Instead of using the method os.system() to execute specific commands, you can do this in a much more elegant way by combining the functions os.listdir() and os.path.isfile() to list only the files of a given directory:

import os, os.path

def listar_arquivos(diretorio):
    listagem = []
    for arquivo in os.listdir(diretorio):
        arquivo = os.path.join(diretorio,arquivo)
        if os.path.isfile(arquivo):
            listagem.append(arquivo)
    return listagem

Or else:

import os, os.path

def listar_arquivos(diretorio):
    return [os.path.join(diretorio,arquivo)
        for arquivo in os.listdir(diretorio)
        if os.path.isfile(os.path.join(diretorio, arquivo))]

Testing:

import os, os.path

def listar_arquivos(diretorio):
    return [os.path.join(diretorio,arquivo)
        for arquivo in os.listdir(diretorio)
        if os.path.isfile(os.path.join(diretorio, arquivo))]

ls = listar_arquivos('/tmp')

# Exibe lista de arquivos
print(ls)

# Exibe a quantidade de arquivos
print(len(ls))

See working on Repl.it

  • it gives an error it says: Typeerror: Join() argument must be str or bytes, not 'list' You know how to fix this?

  • @Hugobarbosa See working on Repl.it.

  • mine does not return anything now, I managed to fix that problem but does not return anything the objective was that function to be inside the method init and when the GUI is booted it detects how many files are available in a given directory like this import os, os.path class test: def listar_files(directory='/books'): listing=[] for file in os.listdir(directory): file=os.path.Join(directory,file) if(os.path.isfile(file): listing.append(file) Return listing def init(self): a=self.list_files print(a) test

  • 1

    How about that ?!

  • It works well another question I created a directory called book and to pass in parameter I have to put /book right? and that when I try to pass it returns the error No such file or directory: '/book'

  • @Hugobarbosa Has already tried ./livro ?

Show 1 more comment

1

According to the documentation of os.system, the return is the Exit status of the command (and not the output of the command itself), and zero generally indicates that the command ran normally with no errors.

The output of the command is sent to the default output (for example, if it runs on the terminal, it will appear on the screen itself).

To get the output of the command the way you want it, use the module subprocess:

import subprocess

cmd = "ls livros -1 | wc -l"    
out = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, text=True)
print(out.stdout)

Since the output of the command is just a number, you can convert it to int if you want:

quantidade = int(out.stdout.strip())

I used strip() to remove the line break at the end, which is also returned in out.stdout.


Obs: subprocess.run added in Python 3.5 - for earlier versions, an alternative is to use Popen:

p1 = subprocess.Popen(["ls", "/c/Users/hkotsubo/", "-1"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["wc", "-l"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()
result = p2.communicate()

print(result[0].decode('ascii'))
# ou se quiser converter para int
quantidade = int(result[0])
print(quantidade)

Browser other questions tagged

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