0

I have a script in python.

I read some path folder from a csv file.

I wish to create a loop to do something like that: "cd" into some folders (I read the path from the csv file) and execute some bash command.

The problem is that I don't know how to go back in the "home" folder to start the loop again.

The code exit with error because don't find the path to folder after chdir in the first folder.

Can someone help me please?

import csv
import os
import subprocess

def subprocess_cmd(command):
    process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
    proc_stdout = process.communicate()[0].strip()
    print(proc_stdout)

with open("esempio.csv", "r") as f_input:
    csv_input = csv.DictReader(f_input)
    
    aaa = []

    for row in csv_input:
        path = row['folder']
        lang1 = row['lang1']
        name1 = row['name1']
        lang2 = row['lang2']
        name2 = row['name2']
        aaa.append(path)
        
    for path in aaa:
        os.chdir(path)
        subprocess_cmd('touch aaa')
marcov
  • 13
  • 2

2 Answers2

0

One way to solve this is to get the current folder before the loop starts and you call chdir() for the first time. Then you can chdir() back to that folder.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

You can use python subprocess library, Using that you can run bash commands and get their output to use inside your code https://docs.python.org/3/library/subprocess.html

ex.subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)