Importing .py files in Google Colab

前端 未结 10 2100
清酒与你
清酒与你 2020-11-28 22:38

Is there any way to upload my code in .py files and import them in colab code cells?

The other way I found is to create a local Jupyter notebook then upload it to C

相关标签:
10条回答
  • A easy way is

    1. type in from google.colab import files uploaded = files.upload()
    2. copy the code
    3. paste in colab cell
    0 讨论(0)
  • 2020-11-28 23:30

    We can do so.

    import sys
    import os
    
    py_file_location = "/content/drive/My Drive"
    sys.path.append(os.path.abspath(py_file_location))
    

    Now you can import it as module in notebook for that location.

    import whatever
    
    0 讨论(0)
  • 2020-11-28 23:31

    In case anyone else is interested to know how to import files/packages from gdrive inside a google colab. The following procedure worked for me:

    1) Mount your google drive in google colab:

    from google.colab import drive
    drive.mount('/content/gdrive/')
    

    2) Append the directory to your python path using sys:

    import sys
    sys.path.append('/content/gdrive/mypythondirectory')
    

    Now you should be able to import stuff from that directory!

    0 讨论(0)
  • 2020-11-28 23:31

    Based on the answer by Korakot Chaovavanich, I created the function below to download all files needed within a Colab instance.

    from google.colab import files
    def getLocalFiles():
        _files = files.upload()
        if len(_files) >0:
           for k,v in _files.items():
             open(k,'wb').write(v)
    getLocalFiles()
    

    You can then use the usual 'import' statement to import your local files in Colab. I hope this helps

    0 讨论(0)
提交回复
热议问题