Home  >  Article  >  Backend Development  >  How to Read Files with Relative Paths in Python Projects?

How to Read Files with Relative Paths in Python Projects?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 03:00:31183browse

How to Read Files with Relative Paths in Python Projects?

Reading a File using a Relative Path in a Python Project

In a Python project with a specific directory structure, retrieving files using relative paths may encounter errors due to the concept of relative paths being tied to the current working directory.

To resolve this, an absolute path can be used instead. However, constructing absolute paths in Python can be cumbersome.

A solution utilizing the file special attribute allows the construction of an absolute path relative to the current script's location:

<code class="python">from pathlib import Path

path = Path(__file__).parent / "../data/test.csv"
with path.open() as f:
    test = list(csv.reader(f))</code>

This method requires Python 3.4 or later due to the pathlib module. For older versions, a work-around exists:

<code class="python">import csv
import os.path

my_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(my_path, "../data/test.csv")
with open(path) as f:
    test = list(csv.reader(f))</code>

Using this technique, files can be retrieved using relative paths within the project structure, regardless of the current working directory.

The above is the detailed content of How to Read Files with Relative Paths in Python Projects?. 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