I am new with python. Currently, i am making a script to compare a file and rename it within specific folder. If the file is csv or exl then rename it to report.csv and move to folder.
My current issue is... my latop worked without issue but when i run script on other laptop then the file name shows with array that it doesn`t allow me to update name correctly: (number, 'filename'). example the output:
("(1, 'desktop", ".ini')") ("(2, 'download data')", '') ("(3, 'pycharm-community-2020.3.5", ".exe')")
My code as below:
import os
from os import path
import shutil
import time
def rename():
os.chdir(r'C:\Users\admin\Downloads')
for filename in enumerate(os.listdir()):
src= filename
ext=os.path.splitext(str(src))
print(ext)
if ext== ".csv":
src=str(filename)
dest=r'C:\ReportDown\LateReport\matic.csv'
print(src)
os.rename(src,dest)
rename()
Could anyone guide me how to compare if the file in folder is csv file then rename it and move to a new folder please ?
THanks very much
You don't need the enumerate()
. Just do for filename in os.listdir():
and it should work.
The enumerate()
function is used for when you want to iterate through both the items and the indices, and in this case you only need the items themselves. If you want to use enumerate, you would have to do for index, filename in enumerate(os.listdir()):
instead, because enumerate gives you tuples of (index, value). Here, your code is converting that entire tuple to a string and then attempting to use that as the filename, which breaks the program.
Also, os.listdir()
should already be giving you strings, so doing str(filename)
is unnecessary.