Home  >  Article  >  Backend Development  >  How to Fix \"FileNotFoundError: No Such File or Directory\" When Opening a CSV File?

How to Fix \"FileNotFoundError: No Such File or Directory\" When Opening a CSV File?

Linda Hamilton
Linda HamiltonOriginal
2024-10-17 16:24:02172browse

How to Fix

Troubleshooting FileNotFoundError: No Such File or Directory

Issue: When attempting to open a CSV file, Python fails to locate the file, resulting in a "FileNotFoundError: [Errno 2] No such file or directory" error.

Code:

<code class="python">import csv

with open('address.csv','r') as f:
    reader = csv.reader(f)
    for row in reader:
        print row</code>

Solution:

The error typically occurs when Python cannot find the specified file in the current working directory. To resolve this, you can provide an explicit path to the file using either a relative or absolute path.

Relative Path:

A relative path specifies the location of the file relative to the current working directory. To use a relative path, simply include the file name without the complete directory path:

<code class="python">import csv

with open('address.csv','r') as f:
    # ...</code>

Absolute Path:

An absolute path provides the complete directory path to the file, regardless of the current working directory. To use an absolute path, prefix the file name with the complete path:

<code class="python">import os

cwd = os.getcwd()  # Get the current working directory
path = os.path.join(cwd, 'address.csv')  # Construct the absolute path
f = open(path, 'r')
# ...</code>

Remember to verify that the file exists at the specified path and that you have the necessary permissions to open it.

The above is the detailed content of How to Fix \"FileNotFoundError: No Such File or Directory\" When Opening a CSV File?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn