Reputation: 533
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
Upvotes: 2
Views: 787
Reputation: 2210
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
Upvotes: 2
Reputation: 2673
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
Upvotes: 3