【问题标题】:Changing name of files with regex in python / tkinter在 python / tkinter 中使用正则表达式更改文件的名称
【发布时间】:2012-10-25 18:57:58
【问题描述】:

我正在尝试使用 python 更改列表中项目的编号,但无论我做什么,它似乎都按数字顺序排列。

假设我在名为 items 的列表中有以下项目

items = ['1. item1', '2. item2', '3. item3', '4. item4']

这样更容易可视化,所以这里是当前顺序

1. item1
2. item2
3. item3
4. item4

从另一个函数中,我将顺序重新排列为:

3. item3
1. item1
4. item4
2. item2

现在,我遇到问题的函数只是将文件重命名为与它们的位置相对应,所以现在是:

1. item3
2. item1
3. item4
4. item2

问题是数字被放回了数字顺序。我的列表项按特定顺序排列,我希望根据它们在列表中的位置对项目进行编号

def order(self, directory):
    i = 1
    #print self.files
    for filename in os.listdir(directory): 
        if filename in self.files: #if the current file in the directory is part of the files list
            newfile = re.sub(r'^[0-9][.]',"",filename) #remove the number and decimal from the beginning
            os.rename(directory + "/" + filename, directory + "/" + str(i) + ". " + newfile) #rename it with a new number and decimal
            i = i + 1
            #print newfile

【问题讨论】:

    标签: python regex loops tkinter


    【解决方案1】:

    尝试改用i - 列表中项目的索引

    os.rename(directory + "/" + filename, directory + "/" + str(self.files.index(filename)) + ". " + newfile)
    

    因为我不确定os.listdir 是如何排列文件的。

    【讨论】:

    • 它有效,但它从 0 而不是 1 开始。所以如果 item3 是第一个位置,它被标记为 0. item 3 而不是 1. item3
    • 好的,我认为这只是将它连接起来。还是习惯了python。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 2021-09-27
    • 1970-01-01
    • 2020-10-09
    • 2011-04-28
    相关资源
    最近更新 更多