Search code examples
pythonsubprocessstrip

Python subprocess list files without "\n"


I'm using subprocess on python to list all the files/folders in one folder:

def subprocess_list(command):
  p = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
  proc_stdout = p.communicate()[0].strip()
  lista.append(proc_stdout.decode('utf-8'))
  retcode = p.wait()
subprocess_list('ls | grep aa')

When I print "lista" I get all the paths in a single-element list:

lista=[aaa\naab\naac\n]

So in order to separate them and get each file I first export them to a .txt, call it back and delete \n

with open('%s/files.txt'%Path_Desktop,'w') as file:
    for item in lista:
        file.write(item)

with open('%s/files.txt'%Path_Desktop) as file:
    content = file.readlines()
content = [x.strip() for x in content]

Print "content":

content=['aaa','aab','aac']

Is there a way to do it directly without the export part? Thanks in advance!


Solution

  • I changed the subprocess for this, don't know if correct or the same but so far it's working well.

    lista = (os.popen('ls | grep aa').read()).split('\n')