Akhil Kodicherla
Akhil Kodicherla

Reputation: 61

Need to split file name into two parts using python

I'm new to python and i am trying to split the filenames that i have read from a directory. I could split the file names from the extension but splitting the name is what i want. Here is my code...can you help me on how to do this. I want to split error log and December with the date( i.e into two parts with error in one and date time into 2nd part.

import os
import os.path
path = 'C:\\Users\\abc\\Desktop\\xls'
text_files = [os.path.splitext(f)[0] for f in os.listdir(path)]
print (text_files)
r = str(text_files)
f = "C:\\Users\\abc\\xls"
f = open('output.txt', 'w')
f.write(r)
f.close()

The exact names of files in the directory are :

  1. Error_Log_December_10_2016_06_19_05 PM.txt
  2. Error_Log_December_15_2016_06_19_05 PM.txt

    around 50 files are present like this which are to be split. Please help.

Upvotes: 1

Views: 1575

Answers (3)

Abdelhakim AKODADI
Abdelhakim AKODADI

Reputation: 1606

If the name always start with Error_Log you simply silice it like an array of characters.

v = "Error_Log_December_10_2016_06_19_05 PM.txt"
print v[0:9]
print v[10:]

Upvotes: 0

Prathik Rajendran M
Prathik Rajendran M

Reputation: 1162

Since you already know how to remove the extension.

v = 'Error_Log_December_15_2016_06_19_05 PM'

a = v.split('_')

errLog = '_'.join(a[0:2])

dateString = '_'.join(a[2:])

Upvotes: 3

Octo
Octo

Reputation: 727

To split the file name between Error_Log and December_... you might want to look at string slicing

Upvotes: 0

Related Questions