1

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.

3
  • 1
    What do you mean by splitting the name? What do you want the result to look like? Commented Dec 26, 2016 at 10:16
  • 1
    Forget about everything else. You just want to split a string in a particular way, the rest is a distraction. See how to create a minimal reproducible example. Commented Dec 26, 2016 at 10:17
  • I want the file to be like this -- Error_Log & December_10_2016_06_19_05 PM Commented Dec 26, 2016 at 10:17

3 Answers 3

3

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:])
Sign up to request clarification or add additional context in comments.

3 Comments

Ahh, I see what you mean. Its because you are not printing the variable, you have no output.
No, it says ----- 'list' object has no attribute 'split'!!
The above code first splits the string with _ and then a list is created. This list is then joined such that you can get the desired two parts of that string. It should work @AkhilKodicherla
0

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

Comments

0

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:]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.