Rename files in python depending on file name -


i'm creating small script rename files inside folder depending on different criteria. have tried use this, stuck @ point

f = []   file in os.walk(outputfolder):     f.append(file) 

in folder (c:\folder) have 2 files: file1.csv, file2.csv

how can create loop goes inside folder , each file

if(file1.csv.find(1) > 0)   else    

thanks have been trying while , cant find solution

for root, dirs, files in os.walk("path/to/folder"):     filename in files:         if "1" in filename:             do_something()         else:             do_something_else() 

when use os.walk, returns generator of directory tree. imagine test directory such:

c:\temp |   \subdir |   |   subfile1.txt |   |   subfile2.txt |   file1.txt |   file2.txt 

list(os.walk) produce:

[("c:\\temp", ["subdir"], ["file1.txt","file2.txt"]),  ("c:\\temp\\subdir", [], ["subfile1.txt","subfile2.txt"])] 

that say, each iteration produces root, list_of_directories_in_root, list_of_files_in_root each subdirectory in original argument. therefore iterate on os.walk same way:

for root, dirs, files in os.walk("path/to/folder"): 

now it's true don't care root or dirs, if have rename file (or etc) you'll need @ least root because you'll doing os.rename(os.path.join(root, filename), "newname.txt").


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -