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



我试图用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'

感谢的帮助

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

试试这个

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

最新更新