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

nightroad
  • 75
  • 1
  • 2
  • 6
  • Possible duplicate of [How to replace (or strip) an extension from a filename in Python?](https://stackoverflow.com/questions/3548673/how-to-replace-or-strip-an-extension-from-a-filename-in-python) – Sylhare Aug 07 '17 at 06:55

1 Answers1

6

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)
adomas.m
  • 383
  • 2
  • 12
cs95
  • 379,657
  • 97
  • 704
  • 746
  • @AGNGazer Good idea! – cs95 Aug 07 '17 at 07:07
  • I would also add a check that the destination file does not exist, possibly printing a warning but proceed instead of crashing...? Couldn't edit previous suggestion to add "warning" to it. But we should leave something to OP to do :) – AGN Gazer Aug 07 '17 at 07:07
  • should be os.getcwd() not os.getcwd('.') other than that. awesome. thank you. – nightroad Aug 07 '17 at 07:12