i'm trying add 59 3 digits in specific position in files in folder, gives error:
valueerror: invalid literal int() base 10: ''
i have checked prints, , indeed 3 char string, containing digits(by looks)
code :
import os def left(s, amount): return s[:amount] def right(s, amount): return s[-amount:] def mid(s, offset, amount): return s[offset:offset+amount] filename in os.listdir("v:\hd_raster\cta2-gua3"): s = mid(filename, 21, 3) print("chars : " + len(s) + " string : " + s) s = int(s) + 59 s = string(s) os.rename(filename,left(filename,21) + s + mid(filename,24,len(filename))
folder screenshot of file names :
your code fragile, , functions left
, mid
, , right
suggest more used language.
among other things, works if current directory contains files, because listdir
returns file name, not it's path. os.rename
fail.
try making little more flexible , bulletproof.
import glob import os fpath = r"v:\hd_raster\cta2-gua3" file_prefix= 'trans_leilao-004-14_0' full_prefix = os.path.join(fpath,prefix) prefix_len = len(full_prefix) files = glob.glob(full_prefix+r"???.*") old_file in files: n = old_file[prefix_len:prefix_len+3] try: new_n = int(n) + 59 except valueerror: print "failed parse filename: " + old_file continue new_file = old_file[:prefix_len] + str(new_n) + old_file[prefix_len+3:] try: os.rename(old_file, new_file) catch oserror: print "failed rename " + old_file
Comments
Post a Comment