在任何应用程序中,检查文件是否存在的能力至关重要。通常,应用程序会执行验证,例如,
在追加/写入文件之前检查文件是否存在。
在读取文件之前,请检查文件是否存在。
python编程语言提供了多种方法来检查文件是否存在。提供功能为'os'的模块,因此在验证文件存在的同时导入os很重要。
-bash-4.2$ ls python_samples test.txt -bash-4.2$ python3 Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> from os import path >>> print(path.exists('test.txt')) True >>> print(path.exists('test1.txt')) False >>>
-bash-4.2$ ls python_samples test.txt -bash-4.2$ python3 Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> print(os.path.isfile('test.txt')) True >>> print(os.path.isfile('test1.txt')) False
上面演示的功能在较低版本的python(<3)中也可用。但是,python 3.4版提供了一个功能pathlibPath.exists()它是从pathlib模块导入的,用于处理文件系统路径。它使用一种面向对象的方法来验证文件是否存在。
-bash-4.2$ ls python_samples test.txt -bash-4.2$ python3 Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import pathlib >>> test_file = 'test.txt' #创建一个文件对象 >>> file = pathlib.Path(test_file)>>> if file.exists(): ... print("file {} exists".format(test_file)) ... else: ... print("file {} does not exists".format(test_file)) ... filetest.txtexists
-bash-4.2$ ls python_samples test.txt -bash-4.2$ python3 Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import pathlib >>> test_file = 'test1.txt' >>> file = pathlib.Path(test_file)>>> if file.exists(): ... print("file {} exists".format(test_file)) ... else: ... print("file {} does not exists".format(test_file)) ... file test1.txt does not exists >>>
使用path.exists验证给定文件是否存在。
使用path.isfile来检查路径是否为文件。
Python 3.4及更高版本提供了一个pathlib模块来验证文件是否存在。
除了上述方法外,还有另一种直接检查Python的方法来检查文件的存在。使用open()打开文件的方法。
-bash-4.2$ ls python_samples test.txt -bash-4.2$ python3 Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> try: ... open('text.txt') ... except: ... print("file does not exists") ... file does not exists
-bash-4.2$ ls python_samples test.txt -bash-4.2$ python3 Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> file_name = 'test.txt' >>> try: ... with open(file_name) as f: ... print("{} exists".format(file_name)) ... except: ... print("{} does not exists".format(file_name)) ... test.txt exists >>>
在上面的示例中使用with可以确保在文件操作后关闭文件。