How to Read Files with Relative Paths in Python Projects?

Patricia Arquette
Release: 2024-10-28 03:00:31
Original
183 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!