2

I would like to get the file name without its extension/suffix with split with specific character.

There are so many jpg files in directory.

for example,

A_list(B)_001.jpg

Stack_overflow_question_0.3.jpg

... and hundreds files in some directory

what I want is to get just the file NAMES without their extensions, like:

A_list(B), 001

Stack_overflow_question, 0.3

but with below code,

import os

path = 'D:\HeadFirstPython\chapter3'
os.chdir(path)

data = open('temp.txt', 'w')

for file in os.listdir(path):
    if file.endswith('.jpg'):
        file = file.split('_')
        print(file, file=data)

data.close()

I got like below result.

['A', 'list(B)', '001.jpg']

['Stack', 'overflow', 'question', '0.3.jpg']

Can this be done with less code?

Thanks and kind regards, Tim

3
  • That isn't very much code as it is... Commented Jul 26, 2014 at 17:30
  • do you want a list of lists or individual lists? Commented Jul 26, 2014 at 17:46
  • I need individual lists :) Commented Jul 26, 2014 at 18:00

2 Answers 2

1
import glob
import os

path = 'D:\HeadFirstPython\chapter3'
os.chdir(path)
with open("temp.txt","w") as f: # with automatically closes your files
   my_l = [x.replace(".jpg","").rsplit("_",1) for x in glob.glob("*.jpg")] # list of lists



with open("temp.txt", "w") as f:
    for x in glob.glob("*.jpg"):
        print x.replace(".jpg", "").rsplit("_", 1) # each list 

The output will look like:

s = "Stack_overflow_question_0.3.jpg"

print s.replace(".jpg", "").rsplit("_", 1)
['Stack_overflow_question', '0.3']

To write to txt file without ",":

with open("temp.txt", "w") as f:  # with automatically closes your files
    my_l = [x.replace(".jpg", "").rsplit("_", 1) for x in glob.glob("*.jpg")]
    for l in my_l:
        f.write(str(l).replace(",", ""))

Using "*.jpg" will search for any file ending with jpg. rsplit("_",1) will split on the rightmost _ and using 1 as maxsplit will only split once. We simply replace the extension with str.replace.

Sign up to request clarification or add additional context in comments.

4 Comments

Can I ask you something to save result into text file? When I save it, Its form is "list" so it contains [ ' , ] like these 4 characters. How can I remove these?
what do you want to do with the contents of the txt file later?
I use an external app which is developed with LISP language. I want to make a script with python based on file name and send it to the external app.
@user3880099, the last part of the answer should do what you want.
0
if file.endswith('.jpg'):
        file = file.rsplit('_',1)
        print file[0],
        print file[1].rsplit('.',1)[0]
        print(file, file=data)

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.