经过第一空间从文件地带文本

问题描述 投票:0回答:3

我试图重新命名约几千文件,只是有自己的代码,文件被命名为这样的:

2834文件

2312文件

982文件

所需的输出:

2834

2312

982

我想重新命名他们的代码是用空格隔开,所以我只需要剥离空格后的文本。

我一直在使用OS试图/水珠/枚举只是在其中重命名按数字顺序,为目录没有被以相同的顺序返回其证明有问题的,所以当我重新命名他们的代码混淆在一起。

python glob file-rename
3个回答
1
投票

你要使用globos。一个简单的例子(与评论),如下所示:

import glob
import os

# iterate over all the files
for files in glob.glob('*.*'):
    try:
        new = files.replace("The file", '') # if there's a match replace names
        os.rename(files, new) # rename the file
        print files, new # just to make sure it's working
    except:
        print 'ERROR!!,', files # to see if there were any errors

或者,如果代码永远是第4个字符,你可以做到以下几点:

import glob
import os

# iterate over all the files
for files in glob.glob('*.*'):
    try:
        os.rename(files, files[0:4]) # rename the file
        print files, new # just to make sure it's working
    except:
        print 'ERROR!!,', files # to see if there were any errors

刚才注意到你的一个例子只有3个字符的代码。一个更好的解决办法可能是使用文件名.find(' ')找到空间准备串片。例如:

import glob
import os

# iterate over all the files
for files in glob.glob('*.*'):
    try:
        os.rename(files, files[0: files.find(' ')]) # rename the file
        print files # just to make sure it's working
    except:
        print 'ERROR!!,', files # to see if there were any errors

3
投票

其他已经展示了如何做到这一点。所以我就建议更好的方式来获得字符串中的第一个词:

filename = "12345 blahblahblah"
sfn = filename.split(" ", 1)
newfilename = sfn[0]

如果这样的字符串不包含“”什么都不会发生,即相同的字符串将被退回。使用find(),而另一方面,将返回-1“”没有找到。并且,切片文件名[0:-1]将采取的最后一个字符关闭,这可能是不期望的效果。双方将导致一个空字符串,如果第一个字符是“”。所以,我提出更好的解决方案:

filename = " 12345 blahblahblah"
sfn = filename.split(None, 1)
newfilename = sfn[0]

如果一些其他的分离比空白需要那么这将是:

filename = "____12345_blahblahblah"
sfn = [x for x in filename.split("_") if x!=""]
newfilename = sfn[0]

然后,这将是完整的重命名为您服务。它不断的延伸和尊重完整路径为好。



import os

def RenameToFirstWord (filename):
    filename = os.path.abspath(filename)
    origfn = filename
    path, filename = os.path.split(filename)
    fn, ext = os.path.splitext(filename)
    # If filename starts with extension separator (hidden files on *nixes):
    if not fn: fn = ext; ext = ""
    sfn = fn.split(None, 1)
    newfn = sfn[0]+ext
    try:
        os.rename(origfn, os.path.join(path, newfn))
    except Exception, e:
        print "Cannot rename '%s' to '%s'!\nError is: '%s'\nand it is ignored!" % (filename, newfn, str(e))


1
投票

使用glob.glob()获得文件的完整列表(我建议给它一个完整路径)。接下来过滤器只用.png.jpg扩展名的文件。接下来提取使用正则表达式的所有号码。如果有多个组它只需数字的第一组。

最后,创建新的文件名,并使用os.rename()重命名文件:

import glob
import os
import re

for filename in glob.glob(r'c:\my folder\*.*'):
    path, name = os.path.split(filename)
    extension = os.path.splitext(name)[1]

    if extension.lower() in ['.jpg', '.png', '.jpeg']:
        digits = re.findall('(\d+)', name)

        if digits:
            new_filename = os.path.join(path, '{}{}'.format(digits[0], extension))
            print "{:30} {}".format(filename, new_filename)     # show what is being renamed
            os.rename(filename, new_filename)

因此,例如:

2834 The file.jpg       2834.jpg
2312 The file.PNG       2312.PNG
982 The file.jpg        982.jpg
1234 test 4567.jpg      1234.jpg
The file 7133123.png    7133123.png
© www.soinside.com 2019 - 2024. All rights reserved.