How to rename the latest csv based on the date column value then move it to different directory in python

Question:

I am able to managed to download a file from a client’s website but since i am using selenium it seems its does have the functionality to change or rename file name before downloading it to the folder also it seems i cant download it to a different location hence i am taking a longer route, that’s how it is once the file is downloaded in the download folder, i will try to read the latest ABC.csv file from download folder and then based on the column value will try to rename it. once, rename the final objective is to move it to a different location. this is something i will be doing once a day on daily basis. Here is the code but needs more polishing. pls help or suggest a better way.

step 1) Read the latest ABC.csv file from download directory
step2) Now,rename the latest ABC.csv file based on the date give in cell B2(like ABC-12-10-2022.csv)
step 3) Move the latest renamed file from c: drive to E: drive

#**This code will retrieve the latest file name**

import glob
import os
import shutil
list_of_files = glob.iglob(r'C:\Users\Eminem\Downloads\*.csv'
# i fear using the above line it will read all the .csv files which i dont want i need only specific csv file like ABC.csv
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)
print(os.path.basename(latest_file))

#**Rename filename based on csv value**

import pandas as pd
import os
path = os.chdir('C:\Users\Eminem\Downloads\*.csv')

df = pd.read_csv(C:\Users\Eminem\Downloads\*.csv', encoding='utf8')
i = 0
for file in os.listdir(path):
new_file_name = df['Market date'].iloc[i]
os.rename(path+'/'+file, path+'/'+new_file_name)
i = i + 1

This is what i have written

import pandas as pd
import os 
list_of_files = glob.iglob('C:\Users\Manish\Downloads\*.csv')
latest_file = max(list_of_files, key=os.path.getmtime)
v = (os.path.basename(latest_file))
df = pd.read_csv(latest_file)
new_name = df['Date'][0]
os.rename(latest_file, r'C:\Users\Manish\DownloadsABC' + 
str(new_name) + '.csv')

only the last step is left to move this new renamed file from c drive to d drive

Asked By: user20432746

||

Answers:

import shutil
import os

shutil.move(r'C:UsersManish'ABC' + str(new_name) + '.csv', r'D:UsersManish'ABC' + str(new_name) + '.csv')
Answered By: Naina