os.path modulo python

Asked

Viewed 171 times

0

Can someone explain to me what happens in these 2 lines?

caminhos = [os.path.join(pasta, nome) for nome in os.listdir(pasta)]
arquivos = [arq for arq in caminhos if os.path.isfile(arq)]

2 answers

1


This code uses the concept of list comprehension.
List comprehension is a syntactic sugar of the python language that follows the following notation:

  [expressão for item in list if condição]

What he does is, for every item of the eternal list case condition is true he executes expression and stores the result in a variable that is a list (the brackets).

Thus, in the first line of the code all names (files and subfolders) within the briefcase are concatenated with the path generating the absolute path. The second line only checks which of these paths are files (note that there may be subfolders).

  • got it, but why the folder and name parameters? it shouldn’t concatenate the two?

  • pasta = r'C:\Users\user\Desktop\mp3' 
caminhos = [os.path.join(pasta, nome) for nome in os.listdir(pasta)]
arquivos = [arq for arq in caminhos if os.path.isfile(arq)]
mp3 = [arq for arq in arquivos if arq.lower().endswith(".mp3")]

  • Name and briefcase was just to follow your nomenclature. Following your folder comment = C:\Users\user\Desktop\mp3

1

Like os.listdir() returns the contents of the folder name by name, without the path, the author used os.path.join() to create strings with the full path.

os.path.join() joins two or more pieces of a file path. It is almost same as concatenating, but there are some differences:

  • If the folder name does not end in bar, it puts the right bar automatically depending on the operating system (/ on linux and \ in windows);
  • If one of the names passed as parameter starts with a slider, it means it is from the root, then folders prior to this are ignored.

The second line uses os.path.isfile() to filter only paths that are files, thus ignoring subfolders and other special items that may be inside the folder.

Browser other questions tagged

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