How can I sequentially rename files in a folder using Python, without renaming files in a messy way?

huangapple go评论101阅读模式
英文:

How can I sequentially rename files in a folder using Python, without renaming files in a messy way?

问题

你好,以下是代码的翻译部分:

  1. import os
  2. path = r'/Desktop/Name'
  3. newpath = r'/Desktop/Name2'
  4. count = 1
  5. for f in os.scandir(path):
  6. if str(f.name).endswith('.png'):
  7. new_file = '' + str(count) + '.png'
  8. src = os.path.join(path, f.name)
  9. dst = os.path.join(newpath, new_file)
  10. os.rename(src, dst)
  11. count += 1
  12. 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:

  1. import os
  2. path = r'/Desktop//Name'
  3. newpath = r'/Desktop/Name2'
  4. count = 1
  5. for f in os.scandir(path):
  6. if str(f.name).endswith('.png'):
  7. new_file = '' + str(count)+'.png'
  8. src = os.path.join(path, f.name)
  9. dst = os.path.join(newpath, new_file)
  10. os.rename(src, dst)
  11. count += 1
  12. 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...

  1. import os
  2. import shutil
  3. path = r'/Desktop/Name'
  4. newpath = r'/Desktop/Name2'
  5. for f in os.scandir(path):
  6. if str(f.name).endswith('.png'):
  7. file_number = int(str(f.name).split('.')[0])
  8. new_file_number = file_number + 1
  9. new_file = '%s.png' % new_file_number
  10. src = os.path.join(path, f.name)
  11. dst = os.path.join(newpath, new_file)
  12. shutil.move(src, dst)
  13. 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...

  1. import os
  2. import shutil
  3. path = r'/Desktop//Name'
  4. newpath = r'/Desktop/Name2'
  5. for f in os.scandir(path):
  6. if str(f.name).endswith('.png'):
  7. file_number = int(str(f.name).split('.')[0])
  8. new_file_number = file_number + 1
  9. new_file = '%s.png' % new_file_number
  10. src = os.path.join(path, f.name)
  11. dst = os.path.join(newpath, new_file)
  12. shutil.move(src, dst)
  13. os.scandir(path).close()

huangapple
  • 本文由 发表于 2023年6月1日 03:59:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376862.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定