[PR] この広告は3ヶ月以上更新がないため表示されています。
ホームページを更新後24時間以内に表示されなくなります。
Python/よく使うコード
やりたいこと | 実装 |
---|---|
文字列長の取得 |
|
文字列の切り取り |
|
指定文字列を含むか |
|
文字列を指定文字で区切る |
|
指定文字で区切った文字列を作る |
|
正規表現による置換 |
|
やりたいこと | 実装 |
---|---|
乱数生成(0~1) |
|
乱数生成(指定範囲) |
|
数値判定 |
|
from datetime import datetime
datetime.today().strftime('%Y%m%d%H%M')
withを使うことで、openしたファイルオブジェクトは終了時に自動でcloseされる
os.path.isfile(filepath)
os.path.isdir(dirpath)
os.path.exists(path)
with open('input.txt', encoding='UTF-8') as f:
str = f.read() # ファイル全体を文字列として取得
line = f.readlines() # ファイル全体をリストとして取得
for l in f: # ファイルを一行ずつ読み込み
print(l)
with open('output.txt', encoding='UTF-8', mode='a') as f: # 新規・上書き
f.write('str')
print('output_string', file=f)
from pathlib import Path
directory = Path(r'./')
for filename in directory.glob(r'**/*.html'):
print(filename)
from pathlib import Path
rootdir = Path(r'./')
for filename in rootdir.glob(r'**/*.html'):
with open(filename, encoding='UTF-8') as file:
for line in file:
if 'grep_string' in line:
print(line)