よしたく blog

ほぼ週刊で記事を書いています

【Google Colab】%%writefile でセルの内容をファイルに書き出す

セルの内容をファイルに書き出す

マジックコマンドの%%writefileを使うことでセルの内容を書き出す事ができる。

%%bash
ls

sample_data
%%writefile sample.txt
test1
test2
%%bash
ls

sample_data sample.txt
%%bash
cat sample.txt

test1 test2

セルの内容をファイルに追記

-aオプションを使うと、追記することができる

%%writefile -a sample.txt
test3

Appending to sample.txt
%%bash
cat sample.txt

test1 test2 test3

応用

ファイルに書き出した内容を呼び出すこともできるので、Pythonプログラムを書き出して別のノートブックから呼び出すと言ったこともできる。

%%writefile hello.py
print('Hello world')
%run hello.py

Hello world
%%writefile pi.py
import math
print(math.pi)
%run pi.py

3.141592653589793