英文:
How can I sequentially rename files in a folder using Python, without renaming files in a messy way?
问题
你好,以下是代码的翻译部分:
import os
path = r'/Desktop/Name'
newpath = r'/Desktop/Name2'
count = 1
for f in os.scandir(path):
    if str(f.name).endswith('.png'):
        new_file = '' + str(count) + '.png'
        src = os.path.join(path, f.name)
        dst = os.path.join(newpath, new_file)
        os.rename(src, dst)
        count += 1
os.scandir(path).close()
希望这可以帮助你解决文件重命名的问题。
英文:
Hi I hope someone can help me,
i'm trying to rename some .png inside a folder,
0.png
1.png
2.png
...
3000.png
the problem is that it processes files in a messy way, for example 10.png renames it to 3.png
Instead it should be 11.png etc.
I would like it to rename like this instead:
0.png rename to -> 1.png
1.png rename to -> 2.png
...
10.png rename to -> 11.png
Some advice?
Thank you
I tried with this:
import os
path = r'/Desktop//Name'
newpath = r'/Desktop/Name2'
count = 1
for f in os.scandir(path):
    if str(f.name).endswith('.png'):
        new_file = '' + str(count)+'.png'
        src = os.path.join(path, f.name)
        dst = os.path.join(newpath, new_file)
        os.rename(src, dst)
        count += 1
 
os.scandir(path).close()
答案1
得分: 0
I'm writing this without testing, but how about this? It should do what you need. It appears that maybe there are files other than *.png files in the directory. If not, then you can simplify this a bit more...
import os
import shutil
        
path = r'/Desktop/Name'
newpath = r'/Desktop/Name2'
        
for f in os.scandir(path):
    if str(f.name).endswith('.png'):
        file_number = int(str(f.name).split('.')[0])
        new_file_number = file_number + 1
        new_file = '%s.png' % new_file_number
        src = os.path.join(path, f.name)
        dst = os.path.join(newpath, new_file)
        shutil.move(src, dst)
         
os.scandir(path).close()
英文:
I'm writing this without testing, but how about this? It should do what you need. It appears that maybe there are files other than *.png files in the directory. If not, then you can simplify this a bit more...
import os
import shutil
    
    path = r'/Desktop//Name'
    newpath = r'/Desktop/Name2'
    
    for f in os.scandir(path):
        if str(f.name).endswith('.png'):
            file_number = int(str(f.name).split('.')[0])
            new_file_number = file_number + 1
            new_file = '%s.png' % new_file_number
            src = os.path.join(path, f.name)
            dst = os.path.join(newpath, new_file)
            shutil.move(src, dst)
     
    os.scandir(path).close()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论