Filenames and paths

Files are organized into directories (also called ‘folders’). Every running program has a ‘current directory’, which is the default directory for most operations. For example, when you create a new file with open, the new file goes in the current directory. And when you open a file for reading, Python looks for it in the current directory. The module os provides functions for working with files and directories. os.getcwd returns the name of current directory. cwd stands for ‘current working directory’. A string like cwd that identifies a file is called a path. A relative path starts from the current directory; an absolute path starts from the topmost directory in the file system. The paths we have seen so far are simple filenames, so they are relative to the current directory. To find the absolute path to a file, you can use abspath, which is in the module os.path.

                       

 

To demonstrate these functions, the following examples ‘walks’ through a directory, prints the names of all the files, and calls itself recursively on all the directories.

 

 

 

from Thinking in Python

原文地址:https://www.cnblogs.com/ryansunyu/p/3988518.html