【问题标题】:Adding extension to multiple files (Python3.5)为多个文件添加扩展名(Python3.5)
【发布时间】:2018-01-14 09:33:31
【问题描述】:

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

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')

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

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

【问题讨论】:

标签: python rename file-extension


【解决方案1】:

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

【讨论】:

  • @AGNGazer 好主意!
  • 我还会添加一个目标文件不存在的检查,可能会打印一个警告但继续而不是崩溃......?无法编辑之前的建议以向其添加“警告”。但是我们应该给 OP 做点什么:)
  • 应该是 os.getcwd() 而不是 os.getcwd('.') 。惊人的。谢谢。
猜你喜欢
  • 1970-01-01
  • 2015-09-08
  • 2011-11-04
  • 2012-12-24
  • 2011-09-01
  • 1970-01-01
  • 2011-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多