Reputation: 3161
I'm trying to add 59 to the 3 digits in a specific position in all the files in my folder, but it gives this error:
ValueError: invalid literal for int() with base 10: ''
I have checked with prints, and is indeed a 3 char string, containing only digits(by the 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]
for 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 :
Upvotes: 1
Views: 303
Reputation: 8215
Your code is very fragile, and functions like left
, mid
, and right
suggest you are more used to another language.
Among other things, this only works if your current directory contains the files, because listdir
only returns the file name, not it's path. So os.rename
will fail.
Try making it a little more flexible and 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"???.*")
for old_file in files:
n = old_file[PREFIX_LEN:PREFIX_LEN+3]
try:
new_n = int(n) + 59
except ValueError:
print "Failed to 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 to rename " + old_file
Upvotes: 1