Python Basic Memo
General
__import__('keyword').kwlist
予約語dir(__builtins__)
Builtin関数
string
- Pythonの文字列フォーマット(formatメソッドの使い方) | ガンマソフト株式会社 まとまってる、ありがたし。
file
- os.path — Common pathname manipulations — Python 3.9.2 documentation
os.path.join(path, *paths)
pathをくっつける。os.path.basename(path)
pathからファイル名だけとる。os.path.exists(path)
,os.path.isdir(path)
,os.path.isfile(path)
存在確認
- os — Miscellaneous operating system interfaces — Python 3.9.2 documentation
- os.environ['HOME'] 環境変数
- os.makedirs(name, mode=0o777, exist_ok=False)
- os.walk(top) ディレクトリを捜査 => (dirpath, dirnames, filenames) dirnamesとfilenamesはlist。次の例が良い。
- 6. Modules — Python 3.9.2 documentation
- sys.path => The module search path
- shutil — High-level file operations — Python 3.9.2 documentation
- shutil.copy(src, dst, *, follow_symlinks=True) コピー
- shutil.move(src, dst, copy_function=copy2)
glob.glob('*.gif') ['1.gif', 'card.gif']
function
- 4. More Control Flow Tools — Python 3.9.2 documentation Keyword Arguments
Definition
def cheeseshop(kind, *arguments, **keywords): print("-- Do you have any", kind, "?") print("-- I'm sorry, we're all out of", kind) for arg in arguments: print(arg) print("-" * 40) for kw in keywords: print(kw, ":", keywords[kw])
Input
cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper="Michael Palin", client="John Cleese", sketch="Cheese Shop Sketch")
Output
-- Do you have any Limburger ? -- I'm sorry, we're all out of Limburger It's very runny, sir. It's really very, VERY runny, sir. ---------------------------------------- shopkeeper : Michael Palin client : John Cleese sketch : Cheese Shop Sketch
argparse
datetime
- datetime — Basic date and time types — Python 3.9.2 documentation
- datetime — Basic date and time types — Python 3.9.2 documentation Format codes
- strftime(format) datetime => str. 諸説ある from, format
- strptime(date_string, format) str => datetime. 諸説ある parse, points
- timedeltaのsecondsとtotal_seconds()
datetime.timedelta(days=1).seconds # => 0 datetime.timedelta(days=1).total_seconds() # => 86400.0
json
- json — JSON encoder and decoder — Python 3.9.2 documentation
- dump()はファイルfpへ、dumps()はstrへ。
- load()はファイルfpから、loads()はstrから。sってstrのsだったのか。
requests
Psycopg – PostgreSQL database adapter
- Psycopg – PostgreSQL database adapter for Python — Psycopg 2.8.7.dev0 documentation
- Installation — Psycopg 2.8.7.dev0 documentation 基本的な使い方
- python - How do I get a list of column names from a psycopg2 cursor? - Stack Overflow 列名
colnames = [desc[0] for desc in curs.description]
logging
- Logging HOWTO — Python 3.9.2 documentation
- 何もしていないとconsoleに。filenameを指定するとファイルに。
import logging logging.warning('Watch out!') # will print a message to the console logging.info('I told you so') # will not print anything
import logging logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG) logging.debug('This message should go to the log file') logging.info('So should this') logging.warning('And this, too') logging.error('And non-ASCII stuff, too, like Øresund and Malmö')
- python - logger configuration to log to file and print to stdout - Stack Overflow
- Consoleにもファイルにも出したい時。
import logging logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[ logging.FileHandler("debug.log"), logging.StreamHandler() ] )
import sys sys.stdout = open('file', 'w') print('test')
Jupyter notebook
%quickref
- Display all dataframe columns in a Jupyter Python Notebook - Stack Overflow
- pandasのdataframeをfullでdisplay
- python - Pop-out / expand jupyter cell to new browser window - Stack Overflow
- pandasのdataframeを別windowsで。
misc
- importlib — The implementation of import — Python 3.9.2 documentation
- ファイル名でimportしたい。importlib.import_module なんか思てたんと違う。ちゃんと読もう。
- python - Lists in ConfigParser - Stack Overflow
- configParserでlist。