简体   繁体   中英

Trouble with os.path() in python

I have a MacOS PyObjC script that gets the filename of a PDF and adds this as the Title metadata to the PDF itself.

I use a key/variable pair of kCGPDFContextTitle and title , which goes into a dictionary of metadata.

If I define title as the entire filepath, taken from sys.argv , then the value correctly appears in the PDF's metadata.

If I define title as a given string, it works.

If I define title as os.path.basename(filename) , then it does not appear in the metadata.

Spaces in the filename are not a factor. The relevant code is:

def setMetadata(filename):
    options = {}    
    title = os.path.basename(filename)  
    titleKey = Quartz.kCGPDFContextTitle

    pdfURL = NSURL.fileURLWithPath_(filename)
    pdfDoc = Quartz.PDFDocument.alloc().initWithURL_(pdfURL)

    options[titleKey] = title
    pdfDoc.writeToFile_withOptions_(filename, options)

if __name__ == "__main__":
    for filename in sys.argv[1:]:
        setMetadata(filename)

If I print() the options dictionary, I can see no structural difference between the working data and the non-working data. The type is string. Other Key/pairs are included, and appear in the metadata without issue.

Weirdly, this was fixed with further text processing.

Using the capitalize() method on the end of the string declaration worked.

title = os.path.basename(filename).capitalize()

Alternatively, I could also get the same result by removing the file ending with os.path.splitext() after declaring title .

title = os.path.basename(filename)
title = os.path.splitext(title)[0]

No idea what was wrong with the original string, but the Gods of CoreGraphics are now satisfied.

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