1

i am trying to use search and replace string in excel file (xls), actually - i need to find string and add before prefix * . For example

1

But i am getting a error:

LVdemact = {'two': two_replaced, 'six': six_replaced, 'five': five_replaced}
NameError: name 'two_replaced' is not defined

Code:

from xlrd import open_workbook
from xlutils.copy import copy
import xlsxwriter

rb = open_workbook("template.xlsx")

# Create an new Excel file and add a worksheet.
wb = xlsxwriter.Workbook('Updated_Workbook1.xlsx')
ws = wb.add_worksheet()

s_orig = rb.sheet_by_index(0)

LVdemact = {'two': two_replaced, 'six': six_replaced, 'five': five_replaced,}

for row in range(s_orig.nrows):
    for col in range(s_orig.ncols):
        if s_orig.cell(row,col).value in LVdemact:
            # s.write(row, col, LVdemact[item])
            ws.write(row, col, LVdemact[s_orig.cell(row,col).value])
        else:
            ws.write(row, col, s_orig.cell(row,col).value)
wb.close()
1
  • You need to at least add something like two_replaced = "two_replaced" before you define LVdemact. Commented Aug 8, 2020 at 6:09

2 Answers 2

1

The issue is in the line - LVdemact = {'two': two_replaced, 'six': six_replaced, 'five': five_replaced,}

variables two_replaced, six_replaced and five_replaced are not defined. Do you want this to be a string ? then define this in this way -

LVdemact = {'two': 'two_replaced', 'six': 'six_replaced', 'five': 'five_replaced'}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use this

df = pd.DataFrame() # Your dataframe

for column in df.select_dtypes('object'):
    df[column] = df[column].str.replace('toreplace','newword')

2 Comments

Once you replace the string in the data frame, how do you write back to your excel sheet though?
df.to_excel('<filename>') sometimes you need to add engine also. i mostly pre install openpyxl and add as argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.