1

Looking to change the file extension from .txt to .csv

import os, shutil

for filename in os.listdir(directory):
    # if the last four characters are “.txt” (ignoring case)
    # (converting to lowercase will include files ending in “.TXT”, etc)
    if filename.lower().endswidth(“.txt”): 
        # generate a new filename using everything before the “.txt”, plus “.csv”
        newfilename = filename[:-4] + “.csv”

        shutil.move(filename, newfilename)
Adrian W
  • 4,563
  • 11
  • 38
  • 52
A-Noob
  • 53
  • 7
  • What is exactly the issue? – galfisher May 22 '18 at 20:41
  • I have many of these txt file and I need them converted. I can use shutil and write them line by line but that would be ineffective. Example shutil.move ('file1.txt', 'file2.txt'). I would prefer to use regex or find an argument that say any .txt in this directory rename to .csv. It going to another program that will ignore the .txt files. – A-Noob May 22 '18 at 21:44
  • Any program that renames *.txt in *.csv need to do this file by file. That's what your program is doing. So, where is the problem? If source and destination are on the same drive `shutil.move()` will just replace the directory entry. That is fast. You should not need to worry for performance. When moving across drives (which is _not_ the case in your scenario), `shutil.move()` will indeed copy the file first, but it will use a block copy and not "line by line". – Adrian W May 22 '18 at 22:24

1 Answers1

2

You can use os and rename.

But let me give you a small advice. When you do these kind of operations as (copy, delete, move or rename) I'd suggest you first print the thing you are trying to achieve. This would normally be the startpath and endpath.

Consider this example below where the action os.rename() is commented out in favor of print():

import os

for f in os.listdir(directory):
    if f.endswith('.txt'):
        print(f, f[:-4]+'.csv')
        #os.rename(f, f[:-4]+'.csv')

By doing this we could be certain things look ok. And if your directory is somewhere else than . You would probably need to do this:

import os

for f in os.listdir(directory):
    if f.endswith('.txt'):
        fullpath = os.path.join(directory,f)
        print(fullpath, fullpath[:-4]+'.csv')
        #os.rename(fullpath, fullpath[:-4]+'.csv')

The os.path.join() will make sure the directory path is added too.

Anton vBR
  • 18,287
  • 5
  • 40
  • 46