python:pythonbasicexamples
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
python:pythonbasicexamples [2020/02/26 15:53] – created admin | python:pythonbasicexamples [2022/10/29 16:15] (current) – external edit 127.0.0.1 | ||
---|---|---|---|
Line 1: | Line 1: | ||
- | ====== Python processing file and directory | + | ====== Python basic examples ====== |
- | ===== os package | + | ===== Python processing file and directory ===== |
+ | ==== os package ==== | ||
* Executing a shell command< | * Executing a shell command< | ||
os.system()</ | os.system()</ | ||
Line 21: | Line 22: | ||
* Remove (delete) the directory path< | * Remove (delete) the directory path< | ||
os.rmdir(path)</ | os.rmdir(path)</ | ||
- | ===== os.path ===== | + | |
==== os.path basic functions ==== | ==== os.path basic functions ==== | ||
* split:< | * split:< | ||
Line 209: | Line 210: | ||
print pathofexecute | print pathofexecute | ||
</ | </ | ||
- | ===== Read and Update File ===== | + | ==== Read and Update File ==== |
<code python> | <code python> | ||
with open(filename, | with open(filename, | ||
Line 217: | Line 218: | ||
with open(filename, | with open(filename, | ||
f.write(content) | f.write(content) | ||
+ | </ | ||
+ | ===== Python Command Line Arguments ===== | ||
+ | refer: https:// | ||
+ | |||
+ | Consider we want to pass two file names through command line and we also want to give an option to check the usage of the script. Usage of the script is as follows − | ||
+ | <code bash> | ||
+ | usage: test.py -i < | ||
+ | </ | ||
+ | Here is the following script to test.py − | ||
+ | <code python> | ||
+ | # | ||
+ | |||
+ | import sys, getopt | ||
+ | |||
+ | def main(argv): | ||
+ | | ||
+ | | ||
+ | try: | ||
+ | opts, args = getopt.getopt(argv," | ||
+ | | ||
+ | print ' | ||
+ | sys.exit(2) | ||
+ | for opt, arg in opts: | ||
+ | if opt == ' | ||
+ | print ' | ||
+ | | ||
+ | elif opt in (" | ||
+ | | ||
+ | elif opt in (" | ||
+ | | ||
+ | print 'Input file is "', | ||
+ | print ' | ||
+ | |||
+ | if __name__ == " | ||
+ | | ||
+ | </ | ||
+ | Now, run above script as follows − | ||
+ | * Option1:< | ||
+ | $ test.py -h | ||
+ | </ | ||
+ | test.py -i < | ||
+ | </ | ||
+ | * Option2:< | ||
+ | $ test.py -i inputfile | ||
+ | </ | ||
+ | Input file is " inputfile | ||
+ | Output file is " | ||
</ | </ |
python/pythonbasicexamples.1582732414.txt.gz · Last modified: 2022/10/29 16:15 (external edit)