Home > Enterprise >  Python to rename files in a directory/folder to csv
Python to rename files in a directory/folder to csv

Time:10-22

I have written a small script to hopefully iterate through my directory/folder and replace act with csv. Essentially, I have 11 years worth of files that have a .act extension and I just want to replace it with .csv

import os

files = os.listdir("S:\\folder\\folder1\\folder2\\folder3")  
path = "S:\\folder\\folder1\\folder2\\folder3\\"  
#print(files)

for x in files:  
    new_name = x.replace("act","csv")  
    os.rename(path x,path new_name)  
    print(new_name)  

When I execute this, it worked for the first five files and then failed on the sixth with the following error:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'S:\\folder\\folder1\\folder2\\folder3\\file_2011_06.act' -> 'S:\\folder\\folder1\\folder2\\folder3\\file_2011_06.csv'

When I searched for "S:\folder\folder1\folder2\folder3\file_2011_06.act" in file explorer, the file opens. Are there any tips on what additional steps I can take to debug this issue?

Admittedly, this is my first programming script. I'm trying to do small/minor things to start learning. So, I likely missed something... Thank you!

CodePudding user response:

In your solution, you use string's replace to replace "act" by "csv". This could lead to problems if your path contains "act" somewhere else, e.g., S:\\facts\\file_2011_01.act would become S:\\fcsvs\\file_2011_01.act and rename will throw a FileNotFoundError because rename cannot create folders.

When dealing with file names (e.g., concatenating path fragments, extracting file extensions, ...), I recommend using os.path or pathlib instead of direct string manipulation.

I would like to propose another solution using os.walk. In contrast to os.listdir, it recursively traverses all sub-directories in a single loop.

import os

def act_to_csv(directory):
    for root, folders, files in os.walk(directory):
        for file in files:
            filename, extension = os.path.splitext(file)
            if extension == '.act':
                original_filepath = os.path.join(root, file)
                new_filepath = os.path.join(root, filename   '.csv')
                print(f"{original_filepath} --> {new_filepath}")
                os.rename(original_filepath, new_filepath)

Also, I'd recommend to first backup your files before manipulating them with scripts. Would be annoying to loose data or see it becoming a mess because of a bug in a script.

CodePudding user response:

import os


folder="S:\\folder\\folder1\\folder2\\folder3\\"
count=1

for file_name in os.listdir(folder):
            source = folder   file_name
            destination = folder   str(count)   ".csv"
             os.rename(source, destination)
             count  = 1
             print('All Files Renamed')
print('New Names are')
res = os.listdir(folder)
print(res)
  • Related