nightroad
nightroad

Reputation: 75

Adding extension to multiple files (Python3.5)

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?.

Upvotes: 5

Views: 13876

Answers (1)

cs95
cs95

Reputation: 402473

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)

Upvotes: 7

Related Questions