LoginSignup
6
10

More than 5 years have passed since last update.

Python 基礎文法(雑)めも (3)

Posted at

2.7ベース。
(1) はこちら
(2) はこちら

関数

def キーワードを使って宣言。

>>> def test(arg):
...    print(arg)
...
>>> test('hoge')

hoge

引数のキーワード指定

>>> test(arg="hogehoge")

hogehoge

可変引数

引数の前にアスタリスクを付けると、キーワード指定しない引数をいくつでも受け付けることができる。

>>> def test(a, b, *args):
...     print(a, b, args)
...
>>> test(1, 2, 3, 4, 5)

(1, 2, (3, 4, 5))

# 空でもOK
>>> test(1, 2)

(1, 2, ())

# キーワード指定はできない
>>> test(1, 2, args = 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test() got an unexpected keyword argument 'args'

未定義のキーワード引数

アスタリスクを2個付けた引数を定義すると、キーワード指定された未定義の引数を取れるようになる。

>>> def test(a, b, **args):
...    print(a, b, args)
...
>>> test(1, 2, c=3, d=4)

1, 2, {'c' : 3, 'd' : 4} # ディクショナリとして代入される

# キーワード無しは NG となる
>>> test(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test() takes exactly 2 arguments (3 given)

*val や **args のような引数は、引数リストの最後に置くようにする

デフォルト引数

>>> def test(arg="hogehoge"):
...    print(arg)
...
>>> test()

hogehoge

ファイル操作

ファイル型

組み込み関数 open() を使う。引数は C の fopen() とほぼ同じ。

>>> f = open("foo.txt", "r")
>>> s = f.read()  # ファイル内容をすべて読み込む
>>> f.close

# python3系では、ファイルのエンコード/デコードに使われる text encoding を指定する引数を持つ
# f = open("foo.txt", "r", encoding='utf-8')

Python2系のopen:
http://docs.python.jp/2/library/functions.html?highlight=open#open

Python3系のopen:
http://docs.python.jp/3/library/functions.html?highlight=open#open

ここでは省略するが、Python3 での Unicode 対応についてはあちこちに情報がある。例えばこれ。
http://postd.cc/why-python-3-exists/

モード

第2引数の意味。

記号 意味
'r' 読み込み用に開く (デフォルト)
'w' 書き込み用に開き、ファイルはまず切り詰められる
'x' 排他的な生成に開き、ファイルが存在する場合は失敗する
'a' 書き込み用に開き、ファイルが存在する場合は末尾に追記する
'b' バイナリモード
't' テキストモード (デフォルト)
'+' ディスクファイルを更新用に開く (読み込み/書き込み)

読み込み

f.read(size)

指定したサイズ(省略するとファイルの終わりまで)をファイルから読み込み、文字列を返す。

f.readline(size)

指定した行数(省略すると1行)を読み込み、文字列を返す。

f.readlines(size)

指定した行数を上限(無ければファイルの最後まで)にファイルから複数行を読み込み、文字列を要素としたリストを返す。

sample:テキストファイルを1行ずつ処理

>>> f = open("test.txt", 'r')
>>> for line in f:
...    print(line, end=" ")   # 1行ずつ表示

書き出し

f.write(str)

文字列を指定してファイルに書き込む。

f.writelines(sequence)

文字列を要素に含むシーケンス(リストなど)を引数に取り、ファイルに書き込む(要素ごとに改行文字は追加されない)。

6
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
10