views:

102

answers:

5
+1  Q: 

split a file name

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?

+2  A: 
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
Martin Beckett
thank you, works great
jesse's solution with the {0} is neater - but with a script it's often better to have simple and readable.
Martin Beckett
@Martin, if you find it unreadable then you should familiarize yourself with that syntax: it's the preferred string formatting solution as of Python 3 http://www.python.org/dev/peps/pep-3101/
Jesse Dhillon
@Jesse - I was just making the point that the most obvious, even if not the shortest, quickest or most elegent - is often the optimal solution for a script that is going to be run once.
Martin Beckett
@Martin, sorry not trying to be a dick. I'm just saying that readability is to some extent a matter of taste, and as this is preferred way to format strings, one should acquire a taste for reading it.
Jesse Dhillon
+3  A: 
fn = "LN0001_07272010_3.dat".split('_')
new_fn = '{0}_JY_{1}'.format(fn[0], fn[1])

Update forgot to add "JY" to new_fn

Jesse Dhillon
Doesn't get the "_JY_" into the new name.
GreenMatt
@GreenMatt, thanks forgot about that.
Jesse Dhillon
+2  A: 
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()
amadain
A: 

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))
tokland
Probably bad choice if LN0001_07272010_3.dat is a multi-gb database file?
Martin Beckett
Edit - sorry ignore the comment, I thought you meant do a line-line copy as an alternative to a rename.
Martin Beckett
A: 
file_name = 'LN0001_07272010_3.dat'
new_file_name = '{0}_JY_{1}'.format(file_name.split('_')[0], file_name.split('_')[1])
Dimitrov