Misunderstanding of python os.path.abspath

后端 未结 3 1947
梦如初夏
梦如初夏 2020-12-24 12:40

I have following code:

directory = r\'D:\\images\'
for file in os.listdir(directory):
    print(os.path.abspath(file))

and I want next outp

3条回答
  •  既然无缘
    2020-12-24 13:22

    Python's native os.listdir and os.path functions are pretty low-level. Iterating through a directory (or a series of descending directories) requires your program to assemble file paths manually. It can be convenient to define a utility function that generates the paths you're going to need just once, so that path assembly logic doesn't have to be repeated in every directory iteration. For example:

    import os
    
    def better_listdir(dirpath):
        """
        Generator yielding (filename, filepath) tuples for every
        file in the given directory path.
        """
        # First clean up dirpath to absolutize relative paths and
        # symbolic path names (e.g. `.`, `..`, and `~`)
        dirpath = os.path.abspath(os.path.expanduser(dirpath))
    
        # List out (filename, filepath) tuples
        for filename in os.listdir(dirpath):
            yield (filename, os.path.join(dirpath, filename))
    
    if __name__ == '__main__':
        for fname, fpath in better_listdir('~'):
            print fname, '->', fpath
    

    Alternatively, there are "higher level" path modules that one can employ, such as py.path, path.py, and pathlib (now a standard part of Python, for version 3.4 and above, but available for 2.7 forward). Those add dependencies to your project, but up-level many aspects of file, filename, and filepath handling.

提交回复
热议问题