0

I'm trying to replace every occurrence of a given string with another string in a directory of excel files.

for (root, dirs, files) in os.walk(DIRECTORY):
    for file in files:
        if file.endswith(".xlsx"):
            path = os.path.join(root, file)
            print("Opening: " + path)
            wb = openpyxl.load_workbook(path)
            for ws in wb.worksheets:
                for row in ws.iter_rows():
                    for cell in row:
                        print(cell.value)
                        if cell.value == target:
                            print("TARGET STRING FOUND")
                            cell.value = replace
                wb.save(wb)

I get AttributeError: 'list' object has no attribute 'endswith' when I run the script.

Thanks for any help

2
  • 2
    And what is the problem/error you have? Commented Nov 6, 2019 at 22:45
  • @luis.parravicini Sorry I forgot to add my error. I updated my question. Commented Nov 6, 2019 at 23:25

2 Answers 2

2

os.walk does not return a sequence of files. It yields (root, dirs, files).

for (root, dirs, files) in os.walk(directory):
    for name in files:
        if name.endswith(".xlsx"):
            path = os.path.join(root, name)
            # the rest of your code here
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

basepath="directory_path"
files = list(filter(lambda x: '.xlsx' in x, os.listdir(basepath)))
for file in files:
    wb = openpyxl.load_workbook(f"{basepath}/file")
    for sheet in wb.worksheets:
        for cell in sheet.iter_rows('C{}:C{}'.format(sheet.min_row,sheet.max_row)):
            print(cell + "\n")
            if cell.value == target:
                cell.value = replace

Comments

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.