使用python重命名文件名 [英] Renaming filenames using python

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

问题描述

我需要简单地将_Manual"这个词添加到我在特定目录中的所有文件的末尾这是我目前正在使用的脚本 - 我没有使用 python 的经验,所以这个脚本是我周围其他脚本的坦率!

I need to simply add the word "_Manual" onto the end of all the files i have in a specific directory Here is the script i am using at the moment - i have no experience with python so this script is a frankenstine of other scripts i had lying around!

它没有给出任何错误消息,但它也不起作用..

It doesn't give any error messages but it also doesnt work..

folder = "C:\Documents and Settings\DuffA\Bureaublad\test"

import os, glob

for root, dirs, filenames in os.walk(folder):
    for filename in filenames:
        filename_split = os.path.splitext(filename) # filename and extensionname (extension in [1])
        filename_zero = filename_split[0]
        os.rename(filename_zero, filename_zero + "_manual")

我正在使用

folder = "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)

但是还是不行..它不打印任何内容,文件夹中也没有任何更改!

but it still doesnt work.. it doesnt print anything and nothing gets changed in the folder!

推荐答案

I.e.它什么都不做?让我们看看:

I. e. it does nothing? Let's see:

folder = "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
        os.rename(fullpath, filename_zero + "_manual" + fileext)

可能会奏效,因为您必须使用完整路径.但我不明白为什么找不到文件时没有例外......

might do the trick, as you have to work with the full path. but I don't understand why there was no exception when the files could not be found...

编辑以将更改放在更显眼的位置:

EDIT to put the change to a more prominent place:

你似乎也走错了路.

使用

folder = r"C:\Documents and Settings\DuffA\Bureaublad\test"

防止\t变成制表符.

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

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