简体   繁体   中英

How to import file from other directory that call subdirectory by using python?

Here is directory map:

home
 |--main.py
 |files
    |-----data
            |-----data.py
            |-----day
                   |-----001.csv
    |-----main
            |-----main.py

The data.py have function will call some files in day as sub-directory such as 001.csv

So, i my main.py want to call this function in data.py

First i use.

import os, sys
lib_path = os.path.abspath('../data')
sys.path.append(lib_path)

from data import get_rt_data

Now i can use get_rt_data that i have imported.

but it still have error:

OSError: File 'day/001.csv' does not exist

I know because my main.py don't know where is 001.csv

but i don't know how to fix it.

I know because my main.py don't where is 001.csv

You're right. So what you need to do is tell main.py where it is. There are several ways to do it. The easiest and best is to pass an absolute path to your code that tries to read day/001.csv . Instead of doing whatever you're currently doing with "day/001.csv", simply use os.path.join(lib_path, "day/001.csv") . Then you've given an absolute path to the file, and your program will know where to find it.

This is kind of abusing the semantics of "lib_path", since you're using it to read data as well, but that seems to be within the nature of the way you have your directories set up. You could solve the semantic issue simply by renaming lib_path to something more accurate like data_path .

There are many other ways you can do this, as well. One idea that comes to mind is to use os.chdir(lib_path) to change the current working directory for your process. Then you can just open day/001.csv as you were trying to do. However, I would advise against this because changing your working directory will change any other relative path, and from the little bit you've described, you don't want to change where the executable works from; you just want to give it a full path to the csv file. The absolute path for 001.csv is the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM