Python 2.5 - Update folder of text files from values stored in a lookup list -
i trying write script update folder of text files based on lookup table. lookup table filename, oldpath, new path. script looks in each text file filename, if there updates oldpath in same line new path. code is:
# import array import * import glob # specify lookup table, keep simple drop in workspaces lookup = "./lookup.csv" # specify workspaces = glob.glob('./*.wor') # open lookup table line in open(lookup).readlines(): # create list store lookup parameters of lookup line lookuplist = [] # split lookup csv @ comma in line.split(","): #print lookuplist.append(i) # use list parameters populate variables (could use list parameters # easier assign variable) filename = lookuplist[0] oldpath = lookuplist[1] newpath = lookuplist[2] # have variables use in replace statement # use workspaces glob loop through workspaces wor in workspaces: # try open the first workspace (text file) f = open(wor, 'r+') # loop through open file line in f.readlines(): # each line check whether current list value (filename) in line if '"' + oldpath + '"' in line: print line # update line, replacing old path new path. line.replace(oldpath, newpath); # close workspace file f.close()
it seems work should, print statement 5 lines end has found correct lines contain search strings lookup, file not updated.
i have read as can find on file opening modes , updating files there no obvious solution. guess issue reading/writing same file. route have chosen open lookup , embed files changed loop. alternative open file , loop through lookup.
happy write updated file out name/folder, issue there if loop through files update, update row based on lookup, when next row of lookup overwrite previous lookup change.
any ideas gratefully received. aplogies if description seems convoluted, happy clarify areas aim not obvious.
thanks
paul
f.readines()
returns list of strings, , iterating on these strings. so, when make edit on string using
line.replace(...)
you not changing text file. rather, changing string have read in.
your approach should write each line temp list, write temp list file, like:
f = open(wor, 'r+') new_lines = [] line in f.readlines(): if '"' + oldpath + '"' in line : line.replace(oldpath, newpath); new_lines.append(line) f.close() file("path/to/your/new/or/temp/file","w") file.write("\n".join(new_lines)) file.close()
Comments
Post a Comment