1

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')
Bronson77
  • 251
  • 2
  • 3
  • 11

1 Answers1

2

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
Mahmoud Elshahat
  • 1,873
  • 10
  • 24