Python文件_文件名与路径

文件名与路径

文件都是按照目录来组织存放的。每一个运行着的程序都有一个当前目录,也就是用来处理绝大多数运算和操作的默认目录。

1.比如当你打开一个文件来读取内容的时候,Python 就从当前目录先来查找这个文件了。

提供函数来处理文件和目录的是 os 模块(operating system缩写)

>>> import os

>>> current = os.getcwd()

>>> current

'/Users/dianze/python'

当前路径为/Users/dianze/python

2.要找到一个文件的绝对路径,可以用 os.path.abspath:

>>> os.path.abspath('output.txt')

'/Users/dianze/python/output.txt'

3.另外,os.path 提供了其他一些函数,可以处理文件名和路径。比如 os.path.exists 会检查一个文件或者目录是否存在:

>>> os.path.exists('output.txt')

True

>>> os.path.exists('output3.txt')

False

4.os.path.isdir 可以来检查一下对象是不是一个目录,而os.path.isfile 就可以检查对象是不是一个文件了。

>>> os.path.isdir('/user')

False

>>> os.path.isfile('output.txt')

True

5.os.listdir 会返回指定目录内的文件(以及次级目录)列表。

>>> import os

>>> current = os.getcwd()

>>> current

'/Users/dianze/python'

>>> os.listdir(current)

['output1.txt', 'c.py', 'output.txt']

6.下面这个例子中,walks 这个函数就遍历了一个目录,然后输出了所有该目录下的文件的名字,并且在该目录下的所有子目录中递归调用自身。

>>> def walk(dirname):

...     for name in os.path.listdir(dirname):

...         path = os.path.join(dirname, name)

...         if os.path.isfile(path):

...            print(path)

...         else:

...            walk(path)

...

例子中的os.path.join 接收一个目录和一个文件名做参数,然后把它们拼接成一个完整的路径。

结束。

原文地址:https://www.cnblogs.com/liusingbon/p/13215840.html