[英]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.