目次
プログラミング教育者。ScratchやPythonを教えています。
工作HardwareHubからのお知らせ
in.txt
First line.
Second line.
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# すべて読み込む
input = open('./in.txt', 'r') # 'r'は既定値であるため省略可能
print input.read()
# バイト単位で読み込み
input = open('./in.txt')
print input.read(1)
# 行単位で読み込み
input = open('./in.txt')
print input.readline()
# イテレータを用いた読み込み
for line in open('./in.txt'):
print line,
# 書き込み
output = open('./out.txt', 'w') # w:上書き, a:追記
output.write('Hello\nWorld!')
output.close()
出力例
$ python sample.py
First line.
Second line.
F
First line.
First line.
Second line.
out.txt
Hello
World!
with-as
リソースを自動的に close
できます。
#!/usr/bin/python
# -*- coding: utf-8 -*-
def Main():
# with-as
with open("./in.txt", 'r') as input:
print input.read()
# close を明示的によぶ
try:
input = open("./in.txt", 'r')
print input.read()
finally:
if input:
input.close()
if __name__ == '__main__':
Main()
0
記事の執筆者にステッカーを贈る
有益な情報に対するお礼として、またはコメント欄における質問への返答に対するお礼として、 記事の読者は、執筆者に有料のステッカーを贈ることができます。
さらに詳しく →Feedbacks
ログインするとコメントを投稿できます。
関連記事
- Python コードスニペット (条件分岐)if-elif-else sample.py #!/usr/bin/python # -*- coding: utf-8 -*- # コメント内であっても、ASCII外の文字が含まれる場合はエンコーディング情報が必須 x = 1 # 一行スタイル if x==0: print 'a' # 参考: and,or,notが使用可能 (&&,||はエラー) elif x==1: p...
- Python コードスニペット (リスト、タプル、ディクショナリ)リスト range 「0から10まで」といった範囲をリスト形式で生成します。 sample.py print range(10) # for(int i=0; i<10; ++i) ← C言語などのfor文と比較 print range(5,10) # for(int i=5; i<10; ++i) print range(5,10,2) # for(int i=5; i<10;...
- ZeroMQ (zmq) の Python サンプルコードZeroMQ を Python から利用する場合のサンプルコードを記載します。 Fixing the World To fix the world, we needed to do two things. One, to solve the general problem of "how to connect any code to any code, anywhere". Two, to wra...
- Matplotlib/SciPy/pandas/NumPy サンプルコードPython で数学的なことを試すときに利用される Matplotlib/SciPy/pandas/NumPy についてサンプルコードを記載します。 Matplotlib SciPy pandas [NumPy](https://www.numpy
- pytest の基本的な使い方pytest の基本的な使い方を記載します。 適宜参照するための公式ドキュメントページ Full pytest documentation API Reference インストール 適当なパッケージ