Home>

Get a list of file names in python, and execute a script to execute the command for each file
I'm trying to make it.
After getting a file list with glob, I was thinking about executing a command with subprocess, but it didn't work.

The file has been acquired, and I want to do something like ls "acquired file name" in subprocess, but an error occurs.
I don't really want to hit ls, but I want to do the exact same thing as processing.

Error message
['test.txt', 'test11.txt', 'conan.txt', 'hero.txt']
conan.txt
ex.py
hero.txt
test.txt
test11.txt
Traceback (most recent call last):
  File "ex.py", line 9, in<module>
    subprocess.call (["ls" + l])
  File "/root/.pyenv/versions/3.6.6/lib/python3.6/subprocess.py", line 267, in call
    with Popen (* popenargs, ** kwargs) as p:
  File "/root/.pyenv/versions/3.6.6/lib/python3.6/subprocess.py", line 709, in __init__
    restore_signals, start_new_session)
  File "/root/.pyenv/versions/3.6.6/lib/python3.6/subprocess.py", line 1344, in _execute_child
    raise child_exception_type (errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'ls test.txt': 'ls test.txt'
Applicable source code
import glob, re, subprocess
ex_file = glob.glob ("*. txt")
print (ex_file)
subprocess.call (["ls"])
for l in ex_file:
    subprocess.call (["ls" + l])
  • Answer # 1

    Shell command execution in Python

    Please here

  • Answer # 2

    This is an error because you are trying to execute a command named"ls test.txt".

    subprocess.call (["ls", l])
    Or
    subprocess.call ("ls" + l, shell = True)