バッチの引数、ユーザ入力
バッチの引数処理はsys.argv
を使う。また、C言語のscanf()
に相当するのがinput()
> python3 sample.py "a" "b" 3 1.0 4
# sample.py
import sys
# 引数取得
args = sys.argv
print(args) # ['sample.py', 'a', 'b', '3', '1.0', '4']
# scanfみたいなものはinput()を使う
name = str( input("your name:"))
age = int( input("your age:"))
print("name : "+name+" ,age="+str(age))
ファイルIO
- ファイルの読み込み
# ファイルの内容を丸ごとread
try :
fr = open("readfile.txt", "r")
print(fr.read())
except FileNotFoundError:
print("file not found")
finally:
print("complete")
fr.close()
# ファイルの内容を1行ごとread
try :
fr = open("readfile.txt", "r")
for line in fr:
print(line)
except FileNotFoundError:
print("file not found")
finally:
print("complete")
fr.close()
# リスト化
try :
fr = open("readfile.txt", "r")
lines = fr.readlines()
except FileNotFoundError:
print("file not found")
finally:
print("complete")
fr.close()
print(lines)
- ファイルの書き込み
# 上書き
try :
fr = open("writefile.txt", "w")
fr.write("aaaa\n")
fr.write("bbbb\n")
except FileNotFoundError:
print("file not found")
finally:
print("complete")
fr.close()
# 追記
try :
fr = open("writefile.txt", "a")
fr.writelines(["dog","cat","rat"])
except FileNotFoundError:
print("file not found")
finally:
print("complete")
fr.close()