-Jupyter Notebook is one excellent IDE for Python Developers
我们可以创建 .py
文件很容易在其他IDE,如PyCharm,VS码,Spyder,只有名称的少数。 许多人认为Jupyter注,可以创造 .ipynb
扩展文件,这是短期的 IPython Jupyter Notebook. 实际上,有多种方式,创建灵活的蟒蛇(.py
)的扩展的文件。 在本文中,我将显示的四个方便的方式来创建Python(.py
)扩展文件,这些文件可直接运行在其他Python Ide。
1. 使用建立在文本编辑器
在Jupyter notebook控制面板中,去"New"菜单, 并选择“Text File” 打开文本编辑器。

图 1. 打开Jupyter notebook内置文本编辑器
首先重命名文件,以 .py扩展 的任何名字,例如,重命名的文件为 hi.py. 在这里要强调的是,只有在您因为在命名 .py文件后,您写代码是将自动缩进,并改变颜色,Jupyter notebook内置的文本编译器能够辨识所写的代码是Python代码。

图2. 首先更改文件的名称
然后,例如在文本编译器中键入以下简单的Python的程序:
def hi(name):
print(f"Hi,{name}!")
然后让我们去 文件 menu in the text editor, and select 保存 and the file will be saved into your working directory.

2. 下载为 .py
我们创建了一个新的笔记本名为 myname
和类型以下脚本:
name = "Tom"
print(f"My name is {name}")
去“File”,选择“Download as”。而后选择Python (.py)。

文件下载到您 default download folder 而不是你的工作目录。
3. 使用魔术函数创建 .py
文件
(1) %%writefile
魔术函数
- 开始Python编码前,
首先,键入%%write filename.py,
. - 如创建一个
hello.py
文件,在Jupyter notebook “Cell”单元中键入以下代码:
%%writefile hello.py
def hello(name):
print(f"Hello, {name}!")
然后点击"运行",其结果如下:

它输出结果"writing hello.py",表明该文件已被保存到您的当前工作目录中。
这是最便捷、最灵活的创建 .py
文件的方法。这样 我们可以将任何notebook中Python代码转换为Python文件。首先,键入%%write filename.py,
接着键入的要写Python代码。
(2) %%file
函数
%%file
类似于 %%writefile
。例如,让我们创建在Jupyter notebook中创建一个"greeting.py"文件。键入和运行以下代码:
%%file greeting.py
def hello(fname,lname):
print(f"Hello, {fname} {lname}!")

总结:
This article introduces you 4 convenient methods to create Python (.py
) extension files directly in Jupyter notebook app, including using built-in text editor, download Jupyter notebook as .py
文件和使用 %%writefile
和 %%file
魔术函数。
如果你有兴趣系统学习Jupyter Notebook课程,您可以参加我的课程: 实用Jupyter Notebook 从入门到专家,此课授课语言文英语。.