为多个文件添加扩展名 (Python3.5)

Adding extension to multiple files (Python3.5)

我有一堆没有扩展名的文件。

file needs to be file.txt

我尝试了不同的方法(没有尝试复杂的方法,因为我只是在学习做一些高级的 python)。

这是我试过的一个:

import os
pth = 'B:\etc'
os.chdir(pth)
for files in os.listdir('.'):
  changeName = 'files{ext}'.format(ext='.txt')

我也尝试了附加、替换和重命名方法,但它们对我不起作用。或者那些对我正在尝试做的事情一开始就不起作用?

我错过了什么或做错了什么?

你需要os.rename。但在那之前,

  1. 检查以确保它们不是文件夹(感谢 AGN Gazer)

  2. 检查以确保这些文件没有已经有扩展名。您可以使用 os.path.splitext.


import os
root = os.getcwd()
for file in os.listdir('.'):
   if not os.path.isfile(file):
       continue

   head, tail = os.path.splitext(file)
   if not tail:
       src = os.path.join(root, file)
       dst = os.path.join(root, file + '.txt')

       if not os.path.exists(dst): # check if the file doesn't exist
           os.rename(src, dst)