【问题标题】:Rename specific files in a folder重命名文件夹中的特定文件
【发布时间】:2021-10-21 19:37:53
【问题描述】:

我正在尝试做一个程序来重命名未按顺序命名的文件,例如:

输入:在我们有这些文件的文件夹中:['spam001.txt', 'spam002.txt', 'spam003.txt', 'spam005.txt', 'spam007.txt']

输出:我想得到相同的文件,命名如下:['spam001.txt', 'spam002.txt', 'spam003.txt', 'spam004.txt', 'spam005.txt']

这是我到目前为止所做的:

import os,shutil

count = 1 
path = '.\\filling in the gaps' #this is the folder where i have the .txt files
files = os.listdir(path)
for i in files:
    if(i[6] != str(count)):
        os.rename(os.path.join(path,i),'spam00%s.txt' %(count))
    count = count+1

我的问题是,当我运行程序时,对于上面提到的输出,我在“填补空白”文件夹中得到['spam001.txt', 'spam002.txt', 'spam003.txt'],我得到 ['spam004.txt', 'spam005.txt'] 在包含“填补空白”文件夹的文件夹中。

基本上,我的程序会重命名文件,但文件最终会放在另一个文件夹中。知道为什么会这样吗? 这是文件所在的位置:

【问题讨论】:

  • 因为rename函数的第二个参数(dest)也使用了path。因此重命名的文件被输出到path定义的目录中。
  • 你的意思是每次在填空文件夹中创建一个新文件夹?
  • 我尝试使用上面编辑过的代码,同样的事情发生了。
  • 运行程序后,我还添加了一张带有 .txt 文件位置的图片
  • 基本上,您需要重命名文件的完整路径,以及重命名文件的存储位置完整路径。这两个路径插入到rename 函数中作为source、dest。目前,由于未指定路径,文件正在输出到脚本的目录。

标签: python python-3.x file-io


【解决方案1】:

这是您的代码的工作版本,提供您想要的结果:

import os

count = 1
path = '.\\filling in the gaps'  # this is the folder where i have the .txt files
files = os.listdir(path)
for i in files:
    if (i[6] != str(count)):
        os.rename(os.path.join(path, i),
                  os.path.join(path, 'spam00%s.txt' % (count))
                  )
    count = count + 1

【讨论】:

    猜你喜欢
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 2012-01-02
    • 2017-11-14
    • 2021-06-21
    • 1970-01-01
    相关资源
    最近更新 更多