Search code examples
pythonpython-3.xglobpython-os

File name not matching with files inside the folder


Greetings I Have Folder named '10k' which contains images named 1_left 1_right as shown below.

enter image description here

My python code to print names of file in Folder:

main_file = '10k'
path = os.path.join(main_file,'*g')
files = glob.glob(path)


#l='10k\10_left.jpeg'
for f1 in files:
    #print(os.path.basename(f1))
    fstr=str(f1)
    print(fstr)

The output is weird when I Print it does not the desired names Output : enter image description here

Please guide me.


Solution

  • @vidit02100, the problem is really very interesting. As I understood from your code, you want to only print the name of image files present inside 10k directory.

    In image, you have not commented the lines which you have commented in the problem's code.

    If you will show full code and tell about the number of images inside 10k directory then it would be much better for me to help you.

    May be your code will be printing the images in reverse order if there will be +10000 images inside 10k. Please check and let me know.

    ✓ As I know, jpg, jpeg & png are the most popular image file extensions that ends with g.

    ✓ So place all these extensions in one list and use another for loop to iterate over it and place your code inside it.

    Please comment if my suggestion doesn't satisfy your need. I will update my answer based on your provided inputs and outputs.

    ✓ Here is your modified code.

    main_file = '10k'
    file_formats = ["png", "jpg", "jpeg"]
    
    for file_format in file_formats:
        path = os.path.join(main_file, '*.' + file_format )
        files = glob.glob(path)
    
        for f1 in files:
            fstr = str(f1)
            print(fstr)