-1

I have a folder full of .txt files and would like to change them to .dat using a method. From what I have researched I have constructed the portion of code below. However, when I run it nothing is changed and they stay as .txt.

def ChangeFileExt(path, curr_ext, new_ext)
   with os.scandir(path) as itr:
     for entry in itr:
        if entry.name.endswith(curr_ext):
            name = entry.name.split('.')
            name = name + '.' + new_ext
            src = os.path.join(path,entry.name)
            dst = os.path.join(path,name)
            os.rename(src, dst)
biqarboy
  • 852
  • 6
  • 15
Charles
  • 17
  • 5
  • What is `entra`? What is `new_name`? Please post your actual code. – Selcuk Feb 05 '21 at 01:27
  • In your code, `entry.name.split('.')` will return a list of strings. Meaning, the variable `name` is a list of string. You need to - (i) Remove the last entry (which is the current file extension) from this list (i.e., `name`). (ii) Append `new_ext` in the `name`. (iii) Construct a single string from the list (i.e., `name`). – biqarboy Feb 05 '21 at 01:32

1 Answers1

0

The following is what i will do, that may be robust in many situations.

import glob
from pathlib import Path
from shutil import copyfile

# glob all the absolute file directories
f_glob = "/[the absolute directory]/*.txt"
ls_f_dirs = glob.glob(f_glob)

# loops through the file directories list for renaming 
# (i will create a new folder storing the copied/renamed file 
# but will not be renaming the original files directly on the existing folder.    
for f_dir in ls_f_dirs:

    # to get the file stem excluding the extension
    f_stem = Path(f_dir).stem      

    # copying the file to new file name in a new absolute directory
    copyfile(f_dir, '/[the new storing absolute directory]/{}.bat'.format(f_stem)) 
hongkail
  • 679
  • 1
  • 10
  • 17