Unexpected double quotes while appending file items to subprocess.run
The real problem here isn't Python or the subprocess
module. The problem the use of subprocess
to invoke shell commands, and then trying to parse the results. In this case, it looks like the command is ls
, and the plan appears to be to read some filesystem paths from a text file (each path on a separate line), and list the files at that location on the filesystem.
Using subprocess
to invoke ls
is really, really, really not the way to accomplish that in Python. This is basically an attempt to use Python like a shell script (this use of ls
would still be problematic, but that's a different discussion).
If a shell script is the right tool for the job, then write a shell script. If you want to use Python, then use one of the API's that it provides for interacting with the OS and the filesystem. There is no need to bring in external programs to achieve this.
import os
with open("list_of_paths.txt", "r") as fin:
for line in fin.readlines():
w = os.listdir(line.strip())
print(w)
Note the use of .strip()
, this is a string method that will remove invisible characters like spaces and newlines from the ends of the input.
The listdir
method provided by the os
module will return a list of the files in a directory. Other options are os.scandir
, os.walk
, and the pathlib
module.
But please do not use subprocess
. 95% of the time, when someone thinks "should I use Python's subprocess
module for this?" the ansewr is "NO".