添加"。"在文件名python

时间:2016-11-21 17:49:33

标签: python append

我有一个包含一些文件的文件夹。文件名的格式为123.createtable.txt124createtable.txt。我想删除文件名中的任何空格,并在数字序列后添加"."(如果尚未存在)。我有点担心如何做后半部分。

import os
path = os.getcwd()
filenames = os.listdir(path) # Returns a list of the files of the directory given by path
for filename in filenames: # For each of the files
    if "." not in filename:
        filename.append (".")
    os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(' ', ''))) # Remove whitespace from filename

2 个答案:

答案 0 :(得分:2)

这段代码远不是极端的,但应该做到这一点:

import os
path = os.getcwd()
filenames = os.listdir(path) # Returns a list of the files of the directory given by path
for filename in filenames: # For each of the files
    newFilename = ""
    for i in range(len(filename)-1):
        if filename[i] in '0123456789' and filename[i+1] not in '0123456789.':
            newFilename = newFilename + filename[i] + '.'
        else:
            newFilename = newFilename + filename[i]
    newFilename = newFilename + filename[-1]
    newFilename = newFilename.replace(' ','')    
    os.rename(os.path.join(path, filename), os.path.join(path, newFilename))

答案 1 :(得分:0)

使用regex

import re
pat = re.compile(r"(\d+)") # pattern for "digits" match

然后使用该模式将其替换为“。”使用re.sub后:

for filename in filenames:
    if any(str(x) in filename for x in list(range(10))):
        newname = re.sub(pat, "\\1.", filename)  # sub numbers
        newname = re.sub(" ", "", newname)       # sub whitespaces
    os.rename(filename, newname)