Search code examples
pythonexcelpandasreplacedirectory

Python: How to find and replace with an input?


I have been attempting to program this find and replace section of my code for quite awhile. Trying two main methods to get this work done. Let me give you some context of what I want to achieve.

Objective: The code will read sheet1 on an Excel spreadsheet. On this Excel spreadsheet are rows of folder paths as shown below. I have repeating folders referred to that I would like to change with another name. One that can be typed and replace that word in the path. This will allow me to reuse the same folder structure with new names for Folder1 + Folder2

folders

Here is my code below

import os
import pandas as pd
from openpyxl import load_workbook
from pandas.core.indexes.base import Index
import fileinput

os. chdir("C:\\Users\\NAME\\desktop")
workbook = pd.ExcelFile('Excel.xlsx')

sheet = workbook.parse('Sheet1')


for col in sheet.values:
    for row in range(len('Folder1')):
        Folder1 = input("Enter Folder1 name")
        try:
        
            os.linesep.replace

        except OSError:
                print ( % Folder1 "addition failed")

        else: 
                print (% Folder1 "addition success")

            
for col in sheet.values:
    for row in range(len('Folder2')):
        Folder2 = input("Enter Folder2 name")
        try:
        
            os.linesep.replace

        except OSError:
                print (% Folder2 "addition failed")

        else: 
                print (%Folder2 "addition success")


for col in sheet.values:
    for row in range(len(col)):
        dir_name = str (col[row])
        
        try:
               os.makedirs(dir_name, exist_ok=True)

        except OSError:
              print ("Creation of the directory %s failed" % dir_name)
        else:
             print ("Successfully created the directory %s " % dir_name)

The result from running this code appears to cause my terminal to ask for the input for both Folder1 + Folder2 several times with no change actually being made when the directories are made. Maintaining their Folder1 and Folder2 names.


Solution

  • You're asking for the user input within your for loop (which is why you're being asked to enter the folder names several times).

    Separately, if you're using pandas, you can just do:

    import os
    import pandas as pd
    
    df = pd.read_excel("C:/Users/Username/Desktop/Excel.xlsx", header=None)
    
    folder1 = input("Enter Folder1 name: ")
    folder2 = input("Enter Folder2 name: ")
    
    output = df[0].str.replace("Folder1", folder1).str.replace("Folder2", folder2)
    
    for folder in output.tolist():
        os.makedirs(folder, exist_ok=True)