[Tutor] Hi all: How do I save a file in a designated folder?

eryk sun eryksun at gmail.com
Tue May 2 21:08:50 EDT 2017


On Tue, May 2, 2017 at 6:09 PM, Michael C
<mysecretrobotfactory at gmail.com> wrote:
> screenshot.save("\test\missed.png")

You probably know that "\t" represents a tab in a string literal, but
there's something about working with a path that causes people to
overlook this. Windows won't overlook it. Control characters, i.e.
characters with an ordinal value below 32, are forbidden in Windows
file names.

Also, you're depending on whatever drive or UNC path is the current
directory. For example:

    >>> os.chdir('C:\\')
    >>> os.path.abspath('/test/missed.png')
    'C:\\test\\missed.png'

    >>> os.chdir('\\\\localhost\C$')
    >>> os.path.abspath('/test/missed.png')
    '\\\\localhost\\C$\\test\\missed.png'

A fully-qualified path must start with the drive or UNC share. For example:

    >>> os.path.abspath('C:/test/missed.png')
    'C:\\test\\missed.png'

    >>> os.path.abspath('//localhost/C$/test/missed.png')
    '\\\\localhost\\C$\\test\\missed.png'

In this case I'm using abspath() to normalize the path, which first
has Windows itself normalize the path via GetFullPathName(). This
shows what Windows will actually try to open or create, given that it
implements legacy DOS rules. For example, it ignores trailing spaces
and dots in the final path component:

    >>> os.path.abspath('C:/test/missed.png ... ')
    'C:\\test\\missed.png'

and DOS devices are virtually present in every directory:

    >>> os.path.abspath('C:/test/nul.txt')
    '\\\\.\\nul'


More information about the Tutor mailing list