0

I'm a beginner in python and I have a problem. Can someone explains what does file for file mean in this code line below?

files = [file for file in os.listdir('myPath')]
for file in files:
    print(file)
ma_brr124
  • 11
  • 3
  • `for file in os.listdir('myPath')` means iterating each element of `os.listdir('myPath')` with `file` as variable, and then you are keeping `file` reference inside list – Moinuddin Quadri Feb 04 '21 at 13:32

1 Answers1

0

"file for file" here is used to refer to each iteration of the loop.

You can use list comprehensions to apply functions over the file value.

For example if you want first 4 characters of all the files in the directory, you would write:

files = [file[:4] for file in os.listdir('myPath')]

Or let's say if you want the extensions for all the files:

files = [file.split('.')[-1] for file in os.listdir('myPath')]

Hope this helped!