csv - Python: renaming files returns the wrong name -
say have folder 1000 csv files names event_1.csv
, event_2.csv
,..., event_1000.csv
.
i in fact have 25 folders , want rename files in such way first 4 characters 0001
first folder, 0002
second, way 0025
. last 4 characters represent event, such 1st event 0001
, second 0002
, way 1000
.
so 1st file in 1st folder changed in fashion: event_1.csv = 00010001.csv
.
anyway code wrong, in first 100 files in 1st folder named 00020000.csv
00020099.csv
, since 0002
should used in 2nd folder only. then, 101st file last, correct filenames: 00010101.csv
00011000.csv
.
this code: wrong that?
import os, sys import glob import csv directory=r'c:\users\myname\desktop\tests' subdir=[x[0] x in os.walk(directory)] subdir.pop(0) n=['0001','0002','0003','0004','0005','0006','0007','0008','0009','0010','0011','0012','0013','0014','0015','0016','0017','0018','0019','0020','0021','0022','0023','0024','0025'] in subdir: n in n: temp_dir=r''+i os.chdir(temp_dir) a=str(n) file in glob.glob("*.csv"): if len(file)==11: event='000'+str(file[6]) newname=a+event os.rename(file, newname + '.csv') if len(file)==12: event='00'+str(file[6:8]) newname=a+event os.rename(file, newname + '.csv') if len(file)==13: event='0'+str(file[6:9]) newname=a+event os.rename(file, newname + '.csv') if len(file)==14: event=file[6:10] newname=a+event os.rename(file, newname + '.csv')
if you're sure names of files, considerably simplify code (as m.t said). try maybe :
for n,i in enumerate(subdir): os.chdir(r''+i) # or whatever folders named m,file in enumerate(glob.glob("*.csv")): newname = "{0:04d}{1:04d}.csv".format(n+1,m+1) os.rename(file, newname)
edit : it's better enumerate.
Comments
Post a Comment