简体   繁体   中英

Python: import files from parent dirs or relative path

Previously, if I need to import files from parent files

I'll do something like

from .some_module import some_class

Now I'm using the code from Udacity ( https://github.com/udacity/artificial-intelligence-for-trading/tree/master/project/project_1 ), specifically, in the .ipynb, the import code is

import sys
!{sys.executable} -m pip install -r requirements.txt

import pandas as pd
import numpy as np
import helper
import project_helper
import project_tests

But this gives error

Invalid requirement: '../../requirements.txt'

and

  File "<ipython-input-4-504bb0e8ad18>", line 3, in <module>
    import helper

  File "G:\Udacity - Artificial Intelligence AI for Trading v1.0.0\artificial-intelligence-for-trading-master\project\project_1\helper.py", line 1
    ../../helper.py

And when I look the actual files, they simply refer to files like this:

在此处输入图片说明

在此处输入图片说明

Is such practice legit? If this is legit, how can I solve the above errors?

You need to create the python file first, then you need to create the functions :
eg

def welc(x):
    print("welcome ",x)

then save it and name it as you like.
then go to another python file in the same directory as the first one and write:

import the_first_file_name  #without .py

the_first_file_name.welc("Abdx")
#Output : welcome Abdx

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