簡體   English   中英

重命名文件夾中的特定文件

[英]Rename specific files in a folder

我正在嘗試做一個重命名未按順序命名的文件的程序,例如:

輸入:在一個文件夾中,我們有這些文件: ['spam001.txt', 'spam002.txt', 'spam003.txt', 'spam005.txt', 'spam007.txt']

output:我想以這樣命名的相同文件結束: ['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

我的問題是,當我運行程序時,對於上面提到的 output,我在“填補空白”文件夾中得到['spam001.txt', 'spam002.txt', 'spam003.txt']並且我得到['spam004.txt', 'spam005.txt']在包含 'filling in the gaps' 文件夾的文件夾中。

基本上,我的程序重命名文件,但文件最終位於另一個文件夾中。 知道為什么會這樣嗎? 這是文件 go 的位置:

在此處輸入圖像描述

這是您的代碼的工作版本,可提供您想要的結果:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM