跳至主要内容

如何在 Python 中检查文件是否存在

通过本简明教程,学习如何在 Python 中检查文件是否存在

使用 AI 探索

在Python中,在尝试使用文件之前检查其是否存在是常见任务,尤其当您需要以编程方式在大量文件上执行读写等文件操作时。本教程将带您了解三种在 Python 中检查文件是否存在的有效方法。

在 Python 中检查文件是否存在的三种方法

在 Python 中,有多种方式可以验证文件是否存在,适用于不同场景和编程风格。下文将介绍三种常用方法,可用于检查文件是否存在。

前提条件:了解当前目录

在整个教程中,我们将演示如何验证文件 my_file.txt 是否存放在文件夹 my_data 中。不过在此之前,了解当前的文件夹结构至关重要,这样您才能有效地在目录中导航。以下是一些标准函数,帮助您在文件夹与目录之间进行导航。

使用 os.getcwd() 获取当前目录

要在 Python 中获取当前工作目录,您可以使用 os 包中的 getcwd() 函数。该函数返回一个表示当前工作目录路径的字符串。例如:

import os

# Get the current working directory
current_directory = os.getcwd()
print("The current working directory is:", current_directory)

使用 os.listdir() 列出目录中的所有文件与文件夹

要在 Python 中列出当前目录下的所有文件夹和文件,您可以使用 os 包中的 listdir() 函数。该函数返回一个列表,包含给定路径目录中的条目名称。例如,我的当前目录中既包含 my_data 文件夹,也包含一个名为 airbnb_data.csv 的数据集。下面我使用 listdir() 将它们列出:

import os

# Get the current working directory
current_directory = os.getcwd()

# List all files and folders in the current directory
entries = os.listdir(current_directory)
print(entries) # Returns ['my_data, 'airbnb_data.csv'] 

方法一:使用 os.path.exists() 函数

现在我们已经学会了如何在目录中导航,接下来就来检查一些文件是否存在吧!os 模块中的 os.path.exists() 函数是检查文件或目录是否存在的直接方式。它简单易用、易于理解。这里我使用一个 if 语句:如果 my_data 中存在 my_file.txt 文件,则返回 “The file exists.”,否则返回 ”The file does not exist”。

import os

# Specify the file path
file_path = 'my_data/my_file.txt'

# Check if the file exists
if os.path.exists(file_path):
   print("The file exists.")
else:
   print("The file does not exist.")

方法二:使用 pathlib.Path.exists() 函数

如果您偏好更现代、面向对象的方式,pathlib 包的 Path.exists() 方法可让您更直观地处理文件路径,并与 Python 的文件处理功能无缝集成。

from pathlib import Path

# Create a Path object
file_path = Path('my_data/my_file.txt')

# Check if the file exists
if file_path.exists():
   print("The file exists.")
else:
   print("The file does not exist.")

方法三:结合文件打开使用 try-except 代码块

另一种方法是将 try-except 代码块与 open() 函数结合使用,在尝试打开文件的同时检查其是否存在。该方法能高效地将存在性检查与文件访问合并起来。

try:
    # Attempt to open the file
    with open('my_data/my_file.txt', 'r') as file:
        print("The file exists.")
except FileNotFoundError:
    print("The file does not exist.")

结论

总之,Python 提供了多种方法来检查目录中是否存在某个文件。您可以根据自己的编程风格和使用场景进行选择!想要了解更多 Python 学习内容,请查看我们的教程 How to Exit Python 或 How to Convert a String to an Integer in Python。

主题