向多个文件添加扩展名(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')

我也尝试了添加,替换和重命名方法,但它对我不起作用。还是那些我不能做的第一件事?

我在想什么或做错了什么?

cs95

你需要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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章