递归替换Excel文件目录中的字符串

问题描述 投票:0回答:2

我正在尝试将所有出现的给定字符串替换为excel文件目录中的另一个字符串。

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)

运行脚本时得到AttributeError: 'list' object has no attribute 'endswith'

感谢您的帮助

python python-3.x openpyxl
2个回答
2
投票

os.walk不返回文件序列。它产生(根,目录,文件)。

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

0
投票

尝试一下

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
© www.soinside.com 2019 - 2024. All rights reserved.