简体   繁体   English

如何使用目录中的 python any.xlsx 文件重命名?

[英]how can i rename using python any .xlsx file in a directory?

I could not find similar question here but how can i rename using python any.xlsx file in a directory?我在这里找不到类似的问题,但是如何使用目录中的 python any.xlsx 文件重命名? The goal is not to hardcode the filename to rename it into something else.目标不是硬编码文件名以将其重命名为其他名称。 Any input or advice is much appreciated.非常感谢任何意见或建议。 Thank you very much.非常感谢你。

What I have tried so far.到目前为止我已经尝试过什么。 What it does is, it creates another excel file but i just need the.xlsx in C:\Test to be rename as Master.xlsx.它的作用是创建另一个 excel 文件,但我只需要将 C:\Test 中的 .xlsx 重命名为 Master.xlsx。

for root, dirs, files in os.walk("C:\Test", topdown=False,):
for name in files:
    base_name, ext = os.path.splitext(name)  #Split name, extension
    if ext in ".xlsx":
        df = pd.read_excel(os.path.join(root, name))
        df.to_excel(os.path.join(root, 'Master.xlsx'), index=False)

You can find all.xlsx files using the glob module and then rename them using the os module.您可以使用 glob 模块找到 all.xlsx 文件,然后使用 os 模块重命名它们。

To get all the files in a specific folder/directory.获取特定文件夹/目录中的所有文件。

files = glob.glob(directory + '/*.xlsx')

then just loop over it to get the list of files and just rename those files using rename().然后遍历它以获取文件列表并使用 rename() 重命名这些文件。

os.rename(file, new_name)

full code:完整代码:

import glob
import os

files = glob.glob('./' + '/*.xlsx')

for file in files:
    os.rename(file, file.replace('.xlsx', '_new.xlsx'))

Use OS client for python使用操作系统客户端 python

import os
os.chdir("C:\Test") #if you are running your code in 'c:\' location you need to do this so that your code will run inside test folder.
for file in os.listdir():
    if file.endswith(".xlsx"):
        os.rename(file, "new_name.xlsx") 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用目录将 xlsx 文件导入 Jupiter 笔记本? - How can I import xlsx file in to Jupiter notebook using directory? 如何使用python重命名目录中的文件 - how to rename file in a directory using python 如何通过Python查找目录中是否存在任何txt文件 - how can I find whether there is any txt file in a directory or not with Python 如何通过 uniqueid 从 xlsx 文件中提取数据并使用 Python 将该数据写入另一个具有相同列名的 xlsx 文件? - How can I pull data by uniqueid from an xlsx file and write that data to another xlsx file with the same column name using Python? 如何使用 Python 将任何目录添加到 PATH? - How Can I add any directory to PATH using Python? 如何快速将python中的xlsx文件转换为csv文件? - how can I quickly convert in python an xlsx file into a csv file? 我可以使用 python 将 xlsb 文件转换为 xlsx 吗? - Can i convert xlsb file to xlsx using python? 使用for循环python重命名目录中的文件名 - Rename file name in a directory using a for loop python 使用Python重命名目录中的所有文件 - rename all file in a directory using Python 如何使用 xlsxwriter 和 python 将图像添加到 xlsx 文件的标题中? - How can i add an image to a header of a xlsx file using xlsxwriter and python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM