This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision Next revision Both sides next revision | ||
other:python:misc_by_jyp [2021/07/07 13:07] jypeter Added the paths/filenames section |
other:python:misc_by_jyp [2021/08/16 14:19] jypeter [Useful python stuff] |
||
---|---|---|---|
Line 2: | Line 2: | ||
<WRAP center round tip 60%> | <WRAP center round tip 60%> | ||
- | You will find on this page some useful, but unsorted, python tips and tricks that can't fit in a section of the main [[other:python:jyp_steps|JYP's recommended steps for learning python]] page | + | You will find on this page some **useful, but unsorted, python tips and tricks** that can't fit in a section of the main [[other:python:jyp_steps|JYP's recommended steps for learning python]] page |
</WRAP> | </WRAP> | ||
Line 49: | Line 49: | ||
* Available since Python version 3.4 | * Available since Python version 3.4 | ||
* [[https://docs.python.org/3/library/pathlib.html#correspondence-to-tools-in-the-os-module|Matching pathlib, and os or os.path functions]] | * [[https://docs.python.org/3/library/pathlib.html#correspondence-to-tools-in-the-os-module|Matching pathlib, and os or os.path functions]] | ||
+ | * [[https://docs.python.org/3/library/shutil.html|High-level file operations]] | ||
+ | |||
+ | === Example: getting the size(s) of all the files in a directory === | ||
+ | |||
+ | <code>$ cd /data/jypmce/TestDir | ||
+ | $ ls -l | ||
+ | total 72 | ||
+ | -rw-r--r-- 1 jypmce ipsl 18147 Jun 25 2012 get_TS_cmip5.py | ||
+ | -rw-r--r-- 1 jypmce ipsl 16152 Jun 21 2012 get_TS_cmip5.py~ | ||
+ | -rw-r--r-- 1 jypmce ipsl 13954 Jul 3 2012 get_TS_cmip5_regular.py | ||
+ | -rw-r--r-- 1 jypmce ipsl 16539 Jun 22 2012 get_TS_cmip5_regular.py~</code> | ||
+ | |||
+ | <code>>>> os.chdir('/data/jypmce/TestDir') | ||
+ | >>> print(os.getcwd()) | ||
+ | /data/jypmce/TestDir | ||
+ | >>> files_list = os.listdir() | ||
+ | >>> files_list | ||
+ | ['get_TS_cmip5.py~', 'get_TS_cmip5_regular.py', 'get_TS_cmip5_regular.py~', 'get_TS_cmip5.py'] | ||
+ | >>> files_sizes = list(map(os.path.getsize, files_list)) | ||
+ | >>> files_sizes | ||
+ | [16152, 13954, 16539, 18147] | ||
+ | >>> sum(files_sizes) | ||
+ | 64792</code> | ||
==== Using command-line arguments ==== | ==== Using command-line arguments ==== | ||
Line 84: | Line 107: | ||
[[https://docs.python.org/3/library/argparse.html|argparse]] (//parser for command-line options, arguments and sub-commands//) is available since Python version 3.2 | [[https://docs.python.org/3/library/argparse.html|argparse]] (//parser for command-line options, arguments and sub-commands//) is available since Python version 3.2 | ||
+ | |||
+ | ==== Using ordered dictionaries ==== | ||
+ | |||
+ | Check the [[https://realpython.com/python-ordereddict/|OrderedDict vs dict in Python: The Right Tool for the Job]] tutorial | ||
/* | /* |