简体   繁体   中英

Python - Printing file name show's full path instead of just the file name

I have some code that prints the file name name however it prints out the whole file path instead of just the name

Here is what it prints now:

C:\Users\edward\OneDrive\Pics\X00DL0027.jpg 

Here is what I want

X00DL0027.jpg

Here is the script:

import json
from PIL import Image
from PIL.ExifTags import TAGS
import os
import os.path
import PIL
from pandas import json_normalize

PIL.Image.MAX_IMAGE_PIXELS = 384000000
rootdir = r"C:\Users\edward\OneDrive\Pics"

newfile = newfile = open('meta.txt', 'w')
newfile.write("Filename                                     |  Image DPI                    | Image Height                  |   Image Width                 |   Image Format                |   Image Mode                  |   Image Frames                |\n")
for file in os.listdir(rootdir):
    # read the image data using PIL
    image = Image.open(os.path.join(rootdir, file))

# extract other basic metadata
info_dict = {
    "Filename": image.filename,
    "Image DPI": image.info['dpi'],
    "Image Height": image.height,
    "Image Width": image.width,
    "Image Format": image.format,
    "Image Mode": image.mode,
    "Frames in Image": getattr(image, "n_frames", 1)
}

line = ""
for label, value in info_dict.items():
    line += f"|{str(value):<30} "  
line += " |"  
newfile.write(line + '\n')

I am not sure what to change within the script.

Any help would be great

使用这个: "Filename": os.path.basename(image.filename),

你可以使用下面的代码

"Filename": image.filename.split('\')[-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM