Bronson77
Bronson77

Reputation: 289

Rename Changing CSV file name in directory

I have a csv file in which the name will always change when exported from an application. I want to rename the csv file using python. Here's what I have so far, but it's definitely wrong.

directory = "/files/"

for file in directory:
    if file.endswith('.csv'):
        os.rename('*.csv', 'tracking.csv')

Upvotes: 1

Views: 830

Answers (1)

Mahmoud Elshahat
Mahmoud Elshahat

Reputation: 1959

i assume you have only one csv file in your directory,

import os
directory = "/files/"

files = os.listdir(directory)

# remove the old tracking file if exists
if 'tracking.csv' in files:
    old_file = os.path.join(directory, 'tracking.csv')
    os.unlink(old_file)

# rename
for file in files:
    if file.endswith('.csv'):
        os.rename(os.path.join(directory, file), os.path.join(directory, 'tracking.csv'))
        break

Upvotes: 2

Related Questions