2

I'm using python3.6 for automatically finding some files in my computer:

import os
criteria = 'something'
file_names = os.popen('find dir -name "*%s*"' % criteria).read()
for file_name in file_names:
   #do something
   pass

The problem is that by doing .read(), all the file names including some criteria is concatenated into one string. How can I get a list of file names as output in order to iterating in the 'for' loop? Thanks a lot

Zézouille
  • 503
  • 6
  • 21
  • Possible duplicate of [How can I split and parse a string in Python?](https://stackoverflow.com/questions/5749195/how-can-i-split-and-parse-a-string-in-python) – Energya Jun 11 '18 at 12:18

2 Answers2

3

In the generic case, you are looking to split a string. The easiest way is to use the built-in .split() method of Python's strings. Example:

>>> ' 1  2   3  '.split()
['1', '2', '3']

For more details, see the documentation

Energya
  • 2,623
  • 2
  • 19
  • 24
  • Thanks. It works with file_names = os.popen('find dir -name "*%s*"' % criteria).read().split('\n')[-1] #-1 because there is a '\n' that I don't need at the end – Zézouille Jun 11 '18 at 12:26
2

Just add split() after read() function as below:

file_names = os.popen('find dir -name "*%s*"' % criteria).read().split()

The thing is read function returns raw string from output say as below:

>>> os.popen('find . -name "*%s*"' % criteria).read()
'./pymp-0kz_4tay\n./pymp-4zfymo3o\n./pymp-k79d3tvz\n./pymp-wq9g900h\n./pymp-v0jvlbzm\n./pymp-lc69tv22\n./pymp-3sqjot2q\n./pymp-fsfv6c3t\n./pymp-

where criteria is pymp in my case. So from the output its clear that I have to split the output by \n which is done by split('\n') method.

Sample Output

>>> file_names = os.popen('find . -name "*%s*"' % criteria).read().split('\n')
>>>
>>>
>>> for file in file_names: print(file)
...
./pymp-0kz_4tay
./pymp-4zfymo3o
./pymp-k79d3tvz
./pymp-wq9g900h
Swadhikar
  • 2,152
  • 1
  • 19
  • 32