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)]
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)]
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).
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:
/
on linux and \
in windows);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.
I got it, thank you very much.
Browser other questions tagged python
You are not signed in. Login or sign up in order to post.
got it, but why the folder and name parameters? it shouldn’t concatenate the two?
– Jose Enrico Guedes de Lima
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")]
– Jose Enrico Guedes de Lima
Name and briefcase was just to follow your nomenclature. Following your folder comment =
C:\Users\user\Desktop\mp3
– absentia