Adding extension to multiple files (Python3.5)

我只是一个虾纸丫 提交于 2020-01-04 09:22:08

问题


I have a bunch of files that do not have an extension to them.

file needs to be file.txt

I have tried different methods (didn't try the complicated ones since I am just learning to do a bit of advanced python).

here is one that I tried:

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

I tried the append, replace and rename methods as well and it didn't work for me. or those don't work in the 1st place with what I am trying to do?

What am I missing or doing wrong?.


回答1:


You need os.rename. But before that,

  1. Check to make sure they aren't folders (thanks, AGN Gazer)

  2. Check to make sure those files don't have extensions already. You can do that with 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)


来源:https://stackoverflow.com/questions/45540785/adding-extension-to-multiple-files-python3-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!