How to import python files in google colaboratory?

为君一笑 提交于 2020-01-23 07:43:09

问题


I am trying to run my program on Google Colab; where my code make use of .py files written seprately.

In normal system I have all files inside one folder and it works using import xyz, but when I tried using same folder in Google drive it gives import error.


回答1:


If you have just 2-3 files, you can try the solution I gave in another question here.

Importing .py files in Google Colab

But if you have something like 5-10 files, I would suggest you put your library on github, then !git clone it to Google Colab. Another solution is to zip all you library files, then modify the first solution by unzipping with !unzip mylib.zip

If those library files are not in a folder structure, just a few files in the same folder. You can upload and save them then import them. Upload them with:

def upload_files():
  from google.colab import files
  uploaded = files.upload()
  for k, v in uploaded.items():
    open(k, 'wb').write(v)
  return list(uploaded.keys())



回答2:


Now in googlecolab(Nov 18) you can upload your python files easily

  • Navigate to Files (Tab on your left panel)
  • Click on UPLOAD Upload your python folder or .py files
  • Use googlecolab book to access the file.

Please check my screenshot below!




回答3:


For example you have a module like this

simple.py
def helloworld():
   print("hello")

Click arrow on left panel => Choose File tab => Upload simple.py In notebook code like this

import simple
simple.helloworld()
=> hello


来源:https://stackoverflow.com/questions/49151168/how-to-import-python-files-in-google-colaboratory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!