Heim  >  Artikel  >  Backend-Entwicklung  >  Wie behebt man „FileNotFoundError: No Such File or Directory“ beim Öffnen einer CSV-Datei?

Wie behebt man „FileNotFoundError: No Such File or Directory“ beim Öffnen einer CSV-Datei?

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

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.

Das obige ist der detaillierte Inhalt vonWie behebt man „FileNotFoundError: No Such File or Directory“ beim Öffnen einer CSV-Datei?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn