user396123
user396123

Reputation: 69

split a file name

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?

Upvotes: 2

Views: 22518

Answers (5)

Jesse Dhillon
Jesse Dhillon

Reputation: 7997

fn = "LN0001_07272010_3.dat".split('_')
new_fn = '{0}_JY_{1}'.format(fn[0], fn[1])

Update forgot to add "JY" to new_fn

Upvotes: 6

Dimitrov
Dimitrov

Reputation: 1

file_name = 'LN0001_07272010_3.dat'
new_file_name = '{0}_JY_{1}'.format(file_name.split('_')[0], file_name.split('_')[1])

Upvotes: 0

tokland
tokland

Reputation: 67900

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))

Upvotes: 0

amadain
amadain

Reputation: 2836

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()

Upvotes: 3

Martin Beckett
Martin Beckett

Reputation: 96167

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

Upvotes: 2

Related Questions