Pythonのアンチョコ
code:paython.py
# comment
# ファイルの読み込み
with open(path) as f:
l = f.readlines()
print(type(l))
print(l)
# ファイルの保存
path_w = 'data/src/test_w.txt'
s = 'New file'
with open(path_w, mode='w') as f:
f.write(s)
with open(path_w) as f:
f.read()
with open(path_w, mode='w') as f:
f.writelines(l)
with open(path_w) as f:
print(f.read())
# OneTwoThree
with open(path_w, mode='w') as f:
f.write('\n'.join(l))
with open(path_w) as f:
print(f.read())
joinとsplit
code:python.py
統合は、連結文字.join(文字列)
splitは文字列.split(分ける文字列)
lines.split('\n')
lines.splitlines()
三項演算子
code:pthon.py
変数 = 値 if 条件式 else 値
insertIndent = "" if indnetLevel == 1 else "\t"*(indnetLevel -1)
正規表現 sub
code:python.py
re.sub(r'(hoge)', '\\1bar', 'hogefoo')
# 数字を続ける場合は
re.sub(r'(第)三', '\g<1>3', '第三')
コマンドライン引数の扱い
code:python.py
import sys
# コマンドライン引数を変数argsに代入
args = sys.argv
if len(sys.argv) < 2:
print("No argument!")
sys.exit()
for
code:python.py
print(n)
for n in range(len(path_loadfile)):
for index,line in enumerate(arr):
for index,line in enumerate(arr,1):
for name in l:
print(name)
else:
print('!!FINISH!!')
if
code:python.py
if 条件式1:
条件式1がTrueのときに行う処理
elif 条件式2:
条件式1がFalseで条件式2がTrueのときに行う処理
else:
すべての条件式がFalseのときに行う処理
論理演算子
code:python.py
x and y xもyもTrueであればTrue
x or y xとyいずれかがTrueであればTrue
not x xがTrueであればFalse、x がFalseであればTrue
倍数チェック
code:python.py
3の倍数:number % 3 == 0
5の倍数:number % 5 == 0
3の倍数かつ5の倍数:number % 15 == 0
配列の長さ
code:python.py
len(リスト)
format
code:python.py
"{}さんの身長は{}cm、体重は{}kgです。".format("山田", 190, 105.3)
"{}さんの身長は{}cm、体重は{}kgです。".format("山田", 190, 105.3)
# 文字列操作 (前後、前だけ、後ろだけ、改行を取り除く)
>> s.strip()
'abc def'
>> s.lstrip()
'abc def \n\r\n \n '
>> s.rstrip()
' \n\r\n \n abc def'
json操作
code:python.py
import json
dict = {"name": "太郎", "age": 23, "gender": "男"}
enc = json.dumps(dict, indent=2, ensure_ascii=False)
print(enc)
ref.
ブール値
code:python.py
flag = False
flag = True
AppleScriptからPythonを呼び出すときの注意点
ターミナルのwhich pythonでフルパスを調べて
code:shell.sh
do shell script "(上記のコマンドで表示されたフルパス) test.py"
とする。
リストの扱い(appendとextend)
リスト.apped(値)
リスト.extend(リストなど)
リストにリストをappendすると入れ子リストになる。
要素をフラットに追加したければextendを使う
型を調べる
$ print(type(hoge))
関数
code:python.py
def func(x, y):
"""A sample function"""
return x + y