用python替换文件名字符 [英] Replacing Filename characters with python

查看:238
本文介绍了用python替换文件名字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码将"_manual"一词添加到文件名加载的末尾. 我需要更改脚本,以便它删除文件名(ES)的最后两个字母,然后将其替换为_ES_Manual 例如:AC-5400ES.txt-> AC-5400_ES_manual.txt

I have some code which adds the word "_manual" onto the end of a load of filenames.. I need to change the script so that it deletes the last two letters of the filename (ES) and then replaces it with _ES_Manual for example: AC-5400ES.txt --> AC-5400_ES_manual.txt

我如何将该功能合并到此代码中?

How would i incorporate that function into this code?

folder = r"C:/Documents and Settings/DuffA/Bureaublad/test"
import os # glob is unnecessary
for root, dirs, filenames in os.walk(folder):
    for filename in filenames:
        fullpath = os.path.join(root, filename)
        filename_split = os.path.splitext(fullpath) # filename and extensionname (extension in [1])
        filename_zero, fileext = filename_split
        print fullpath, filename_zero + "_manual" + fileext
        os.rename(fullpath, filename_zero + "_manual" + fileext)

推荐答案

尝试一下:

import os
pathiter = (os.path.join(root, filename)
    for root, _, filenames in os.walk(folder)
    for filename in filenames
)
for path in pathiter:
    newname =  path.replace('ES.txt', '_ES_manual.txt')
    if newname != path:
        os.rename(path,newname)

这篇关于用python替换文件名字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆