我正在尝试更改五个文件的标题,以显示该文件中以“ _”分隔的列中的第一个和最后一个值
例如,在一个列中,如果我具有值0001,0002,0003,0004,我想查找第一个和最后一个值并将文件标题更改为0001_0004
files=os.listdir(os.getcwd())
for file in files:
if file.endswith('.xlsx'):
print(file)
try:
wb=openpyxl.load_workbook(os.path.join(os.getcwd(),file))
print('reading workbook'+file)
ws=wb['Sheet1']
for row in range(7, ws.max_row+1):
cell = ws.cell(row = row, column = 7)
#code to change name
wb.save(os.path.join(os.getcwd(),file))
print('file title changed')
except Exception as e:
print(e)
答案 0 :(得分:2)
files=os.listdir(os.getcwd())
all_xls = []
for f in files:
if f.endswith('.xlsx'):
all_xls.append(f.replace('.xls', '')
all_xls.sort()
first_file = all_xls[0]
last_file = all_xls[-1]
#Do your renaming using os.rename('src', 'dest')
这只是我能想到的一种快速解决方案,它不是最佳解决方案,您可以对其进行调整以更快地获得所需的结果。
希望这会有所帮助。
答案 1 :(得分:0)
path = os.getcwd()
files = os.listdir(os.getcwd())
for filename in files:
if filename.endswith('.xlsx'):
print(filename)
wb = openpyxl.load_workbook(os.path.join(os.getcwd(),filename), data_only = True)
ws = wb['Sheet1']
final = ws.max_row
original_file = str(filename)
cell = ws['G7'].value
filenamep1 = cell
cell = ws.cell(row = final, column = 7).value
filenamep2 = cell
os.rename(original_file, path + '\\' + filenamep1 + '_' + filenamep2 + '_' +
original_file)
print("All files renamed")
这就是我最终用来重命名文件的原因