我想要重命名的文件夹中有数百个 CSV 文件。有一个 Excel 工作表,其中包含要重命名的文件夹中的文件名称。
示例:
让我们考虑一个名为 TestData_30April.csv
的 CSV 文件,该文件位于文件夹中。我希望将其重命名为 0.25-TestData_30April.csv
。 X 列中的 Excel 工作表包含要重命名的名称(0.25-TestData_30April.csv)
。
同样,Excel 工作表包含要重命名的文件夹中所有文件的名称。
这是代码:
import os
import xlrd
#Excel Sheet containing name of files to be renamed in that folder
path="C:\\Users\\Desktop\\Test_Data\\Test_Summary.xlsx"
wb = xlrd.open_workbook(path)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
#In excel sheet column X or col_values(23) contains the file name to be renamed
print(sheet.col_values(23))
#Below line contains all the csv sheets
os.rename('C:\\Users\\Desktop\\AllData',sheet.col_values(23))
我希望将文件夹中的文件重命名为 Excel 工作表中的名称。如何将 Excel 工作表中的数据映射到该文件夹以便进行重命名?
最佳答案
迭代列中的所有值。删除名称中的数字前缀以获得原始名称,然后进行重命名。
dir = r'C:\Users\Desktop\AllData'
new_names = sheet.col_values(23)
for new_name in sheet.col_values(23):
if '-' in new_name:
old_name = new_name.split("-")[1]
if os.path.isfile(os.path.join(dir, old_name)):
os.rename(os.path.join(dir, old_name), os.path.join(dir, new_name))
关于python - 更改文件夹中 csv 文件的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55946227/