0

My using python only occasionally; so I understand the basic concepts; but today I ran into a piece of code ... that I simply don't understand:

I was looking for an efficient way to do "find" via python; and this SO question shows this answer:

paths = [line[2:] for line in subprocess.check_output("find . -iname '*.txt'", shell=True).splitlines()]

And yes, it works for me; and is much faster compared to os.walk; so I intended to use it. But I have to admit: I don't understand what it is doing; especially the 'line[2:]' part ... wtf?!

I tried to use google/so to find the answer; well, searching for "python line" didn't help at all ... so, probably stupid question: what does it mean?

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • What is happening is you are slicing the `./` off the strings returned from the `find` command, find will return `'./filename'`, slicing the first two chars off removes the `./` so you are just left with the filename, it is strings returned that are being sliced not lists – Padraic Cunningham Aug 12 '15 at 13:40

1 Answers1

6

line[2:] is using slice-notation to make a sub-string of line from element [2] to the end of the string.

This is wrapped in a list comprehension that will do the above operation for every line that was returned from subprocess.check_output

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218