简体   繁体   English

Python:如何重命名文件夹中的文件?

[英]Python: how to rename a file in a folder?

I have a list of file like the following我有一个如下所示的文件列表

'TRIAL_20134_75690_TOTAL_2018-08-12-17-18.csv'

I want to rename them the parte after the last underscore, such as the file will be renamed like:我想在最后一个下划线之后将它们重命名为 parte,例如文件将重命名为:

'TRIAL_20134_75690_TOTAL.csv'

Use os.rename from the os library to do the renaming.使用os库中的os.rename进行重命名。

To get the sting up to the last index of an underscore ( _ ), use the rindex method of string .要获得下划线 ( _ ) 的最后一个索引,请使用stringrindex方法。

You also need to concatenate the extension back on.您还需要重新连接扩展名。

Ie IE

import os
f = 'TRIAL_20134_75690_TOTAL_2018-08-12-17-18.csv'
os.rename(f, f[:f.rindex('_'] + '.csv')

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM