Hello
How do i write a python script to split a file name
eg
LN0001_07272010_3.dat
and to rename the file to LN0001_JY_07272010
?
also how do i place a '|' and the end of each line in this file(contents) each line is a record?
Hello
How do i write a python script to split a file name
eg
LN0001_07272010_3.dat
and to rename the file to LN0001_JY_07272010
?
also how do i place a '|' and the end of each line in this file(contents) each line is a record?
name = "LN0001_07272010_3.dat"
parts = name.split('_') # gives you ["LN0001","07272010","3.dat"]
newname = parts[0] + "_STUFF_" + parts[1] ... etc
For rename you can either use the python filesystem function,
Or you can use python print to spit out a set of rename commands for your OS, capture that to a batch/shell file and AFTER checking that it looks correct - run it.
print "mv ",name,newname # gives; mv LN0001_07272010_3.dat LN0001_JY_07272010
fn = "LN0001_07272010_3.dat".split('_')
new_fn = '{0}_JY_{1}'.format(fn[0], fn[1])
Update forgot to add "JY" to new_fn
filename="LN0001_07272010_3.dat"
newfilename=filename.split("_")[0]+"_JY_"+filename.split("_")[1]
linearr=[]
for line in open(filename).readlines():
linearr.append(line+"|")
f=open(newfilename, "w")
for line in linearr:
f.write(line)
f.close()
Because in-place operations are usually a bad idea, here is a code that creates a new file leaving the original unchanged:
fn = "LN0001_07272010_3.dat"
fn1, fn2 = fn.split("_")[:2]
new_fn = "_".join([fn1, "JY", fn2])
open(new_fn, "w").writelines(line.rstrip()+"|\n" for line in open(fn))
file_name = 'LN0001_07272010_3.dat'
new_file_name = '{0}_JY_{1}'.format(file_name.split('_')[0], file_name.split('_')[1])