简体   繁体   English

如何使用python从其他调用子目录的目录中导入文件?

[英]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 data.py具有功能将在一天中调用某些文件作为子目录,例如001.csv

So, i my main.py want to call this function in data.py 所以,我我的main.py想在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. 现在,我可以使用已导入的get_rt_data。

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 我知道是因为我的main.py不知道001.csv在哪里

but i don't know how to fix it. 但我不知道如何解决。

I know because my main.py don't where is 001.csv 我知道是因为我的main.py不在001.csv

You're right. 你是对的。 So what you need to do is tell main.py where it is. 因此,您需要告诉main.py它在哪里。 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 . 最简单,最好的方法是将绝对路径传递给尝试读取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") . 不用使用“ day / 001.csv”来完成当前工作,只需使用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. 这是在滥用“ lib_path”的语义,因为您也正在使用它来读取数据,但这似乎在设置目录的方式之内。 You could solve the semantic issue simply by renaming lib_path to something more accurate like data_path . 您只需将lib_path重命名为更准确的数据(例如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. 想到的一个想法是使用os.chdir(lib_path)更改您的进程的当前工作目录。 Then you can just open day/001.csv as you were trying to do. 然后,您可以按照自己的day/001.csv打开day/001.csv 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. 您只想为其提供csv文件的完整路径。 The absolute path for 001.csv is the way to go. 001.csv的绝对路径是001.csv的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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