在Python中重命名目录中的多个文件[重复]

本文翻译自:Rename multiple files in a directory in Python [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

I'm trying to rename some files in a directory using Python. 我正在尝试使用Python重命名目录中的一些文件。

Say I have a file called CHEESE_CHEESE_TYPE.*** and want to remove CHEESE_ so my resulting filename would be CHEESE_TYPE 假设我有一个名为CHEESE_CHEESE_TYPE.***的文件,并且想删除CHEESE_因此我的结果文件CHEESE_TYPE

I'm trying to use the os.path.split but it's not working properly. 我正在尝试使用os.path.split但它无法正常工作。 I have also considered using string manipulations, but have not been successful with that either. 我也考虑过使用字符串操作,但也没有成功。


#1楼

参考:https://stackoom.com/question/BZl5/在Python中重命名目录中的多个文件-重复


#2楼

此命令将在当前目录下的所有文件删除初始 “CHEESE_”的字符串,用重命名

$ renamer --find "/^CHEESE_/" *

#3楼

This sort of stuff is perfectly fitted for IPython, which has shell integration. 这种东西非常适合IPython,它具有shell集成。

In [1] files = !ls
In [2] for f in files:
           newname = process_filename(f)
           mv $f $newname

Note: to store this in a script, use the .ipy extension, and prefix all shell commands with ! 注意:要将其存储在脚本中,请使用.ipy扩展名,并在所有shell命令前加上! .

See also: http://ipython.org/ipython-doc/stable/interactive/shell.html 另见: http//ipython.org/ipython-doc/stable/interactive/shell.html


#4楼

The following code should work. 以下代码应该有效。 It takes every filename in the current directory, if the filename contains the pattern CHEESE_CHEESE_ then it is renamed. 它接受当前目录中的每个文件名,如果文件名包含模式CHEESE_CHEESE_ ,则重命名。 If not nothing is done to the filename. 如果没有对文件名做任何事情。

import os
for fileName in os.listdir("."):
    os.rename(fileName, fileName.replace("CHEESE_CHEESE_", "CHEESE_"))

#5楼

Here is a more general solution: 这是一个更通用的解决方案:

This code can be used to remove any particular character or set of characters recursively from all filenames within a directory and replace them with any other character, set of characters or no character. 此代码可用于从目录中的所有文件名中递归删除任何特定字符或字符集,并将其替换为任何其他字符,字符集或无字符。

import os

paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk('C:\FolderName')
        for filename in filenames)

for path in paths:
    # the '#' in the example below will be replaced by the '-' in the filenames in the directory
    newname = path.replace('#', '-')
    if newname != path:
        os.rename(path, newname)

#6楼

Here's a script based on your newest comment. 这是基于您最新评论的脚本。

#!/usr/bin/env python
from os import rename, listdir

badprefix = "cheese_"
fnames = listdir('.')

for fname in fnames:
    if fname.startswith(badprefix*2):
        rename(fname, fname.replace(badprefix, '', 1))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值