我正在尝试将所有出现的给定字符串替换为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