• 周四. 4月 25th, 2024

python保存jupyter notebook 代码为.py格式

城主

12月 9, 2019

jupyter notebook 在写python代码时非常方便,当然,也可以将 jupyter notebook 代码方便地保存为.py格式。

Jupyter notebook 源自 Fernando Perez 发起的 IPython 项目。IPython 是一种交互式 shell,与普通的 Python shell 相似,但具有一些很好的功能(例如语法高亮显示和代码补全)。

在jupyter notebook里输入:

%%writefile train.py 
train_v = 10 
def train_add(list_n):
    train_sum = 0
    for i in range(len(list_n)):
        train_sum += list_n[i]
    return train_sum
list_n = [2,3,4,5,6]
print(train_add(list_n))

%%writefile train.py 表示将文件保存为trian.py的文件,运行之后会显示:

Writing train.py

%run train.py 20

运行%run 表示运行某个python文件

import os
os.path.abspath('.')  #显示当前路径
'F:\\02.python'

os.remove(‘train.py’) #移除文件

需要删除的话,使用remove来删除。

以上为jupyter notebook 在写python代码时将 jupyter notebook 代码方便地保存为.py格式的方法。

阅读  Windows和Linux下,python命令行显示同时重定向到文件