Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How does this next work?
#1
Using next() with os.walk() I can very neatly and easily get all files in a folder and ignore other folders if present.

I have to say, I don't really understand what's happening, but it works great!

files = next(os.walk(path2talkfiles))[2]
files.sort()
Could someone elaborate a little?
Reply
#2
os.walk(path2talkfiles) is an iterator. It behaves like a sequence of tuples
Output:
(root, dirs, files) (root, dirs, files) (root, dirs, files) (root, dirs, files) (root, dirs, files) (root, dirs, files) ...
The next() function returns the next item of an iterator and advances the iterator. In this case it returns the first tuple (root, dirs, files). Taking the [2] element in this tuple is a list of files in the root directory.
Pedroski55 likes this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020