《Python Quick start ( The first 3 edition )》 Naomi · Sead
11.1.2 Command line arguments
argvtest.py The contents are as follows
import sys
def main():
print(sys.argv)
main()
Command line parameters will be stored in the form of string list sys.argv in
# python argvtest.py arg1 arg2 arg3
['argvtest.py', 'arg1', 'arg2', 'arg3']
11.1.3 Script input / Redirection of output
Generally speaking , Command line
python script.py arg1 arg2 arg3 < infile > outfile
The operation effect is , hold input or sys.stdin All operations of are directed from infile, hold print or sys.stdout All operations of are directed to outfile. This effect is like sys.stdin Set it to read-only mode ('r') Of infile, take sys.stdout Set to write only ('w') Mode outfile. The following commands have the same effect ,
notes : hold ">" Change it to “>>” The output result will be appended to outfile At the end of , Instead of overwriting the output file .
example ,replace.py The contents are as follows
import sys
def main():
contents = sys.stdin.read()
sys.stdout.write(contents.replace(sys.argv[1],sys.argv[2]))
main()
infile.txt The contents are as follows
one two zero
zero three four
a s dfgh aaaaa
perform python3 replace.py zero 0 <infile.txt> outfile.txt,outfile.txt The contents are as follows
one two 0
0 three four
a s dfgh aaaaa
Carry on python3 replace.py a A <infile.txt>> outfile.txt
# cat outfile.txt
one two 0
0 three four
a s dfgh aaaaa
one two zero
zero three four
A s dfgh AAAAA
Combine pipe symbols , The following command will put "a" Replace with "A", "one" Replace with "1" Output to outfile.txt
[[email protected] ~]# python3 replace.py a A <infile.txt | python3 replace.py one 1 > outfile.txt
[[email protected] ~]# cat outfile.txt
1 two zero
zero three four
A s dfgh AAAAA
[[email protected] ~]#
11.1.4 argparse modular
argparse modular _wy_hhxx
11.1.5 fileinput Use of modules
fileinput modular _wy_hhxx
11.2 Let the script in UNIX Under direct operation
Add the following command to the first line of the script file , And modify the file attributes correctly , namely chmod +x <filename>
#!/usr/bin/env python
My test environment uses python3 And not by default , So we need to use #!/usr/bin/env python3
[[email protected] ~]# ls -l test1.py
-rwxr-xr-x 1 root root 333 Jul 3 12:01 test1.py
[[email protected] ~]# ./test1.py
in decorate function, decorating myfunction
Executing myfunction
hello
[[email protected] ~]#
You can also use python3 Execution path of
[[email protected] ~]# whereis python3
python3: /usr/local/python3 /usr/local/python3/bin/python3.9 /usr/local/python3/bin/python3.9-config /usr/local/python3/bin/python3
[[email protected] ~]#
Try adding any of the following lines at the beginning of the script , Can be executed directly
#!/usr/bin/env python3
#!/usr/local/python3/bin/python3.9
#!/usr/local/python3/bin/python3
11.5 Programs and modules
It's easy to combine script code with modules , That is, add the following condition test to the main control function :
if __name__ == '__main__':
main()
else:
# Initialization code of this module
If called as a script , The current module name at runtime will be __main__, Then the master function will be called main. If the conditional test has been imported into the interactive session or other modules , Then the module name will be its file name .
12.2 Path and path name
12.2.2 Current working directory
os modular
os.curdir # return '.'
os.getcwd() # Returns the current working path pwd
os.chdir('somepath') #cd xxx
os.listdir(os.curdir) #ls
>>> import os
>>> os.curdir
'.'
>>>
>>> os.getcwd()
'/root'
>>>
>>> os.chdir('/opt')
>>> os.getcwd()
'/opt'
>>> os.listdir(os.curdir)
['rh', 'containerd', 'cni']
>>>
>>> os.listdir('/opt')
['rh', 'containerd', 'cni']
>>>
12.2.3 use pathlib Module access directory
>>> import pathlib
>>> pathlib.Path()
PosixPath('.')
>>> cur_path = pathlib.Path()
>>> cur_path.cwd()
PosixPath('/opt')
>>>
pathlib Don't offer anything like os.chdir() That changes the function of the current directory , But you can create path Object to create a new folder
12.2.4 Processing of path names
os.path.join The function interprets parameters as a series of directory names or file names
os.path.split Function will return a tuple consisting of two elements , Split the path into file names ( The name of a single file or directory at the end of the path ,basename) And the rest
os.path.dirname The function returns only the path part
os.path.basename The function returns only the file name in the path
os.path.splitext Function can handle file extensions identified by periods
>>> import os
>>> os.path.join('bin','utils','disktools')
'bin/utils/disktools'
>>>
>>> os.path.split('/bin/utils/disktools/')
('/bin/utils/disktools', '')
>>> os.path.split('/bin/utils/disktools')
('/bin/utils', 'disktools')
>>>
>>> os.path.dirname('/bin/utils/disktools/')
'/bin/utils/disktools'
>>> os.path.dirname('/bin/utils/disktools')
'/bin/utils'
>>> os.path.basename('/bin/utils/disktools')
'disktools'
>>>
>>> os.path.splitext('/bin/utils/disktools/pic.jpg')
('/bin/utils/disktools/pic', '.jpg')
>>>
12.2.5 use pathlib Processing pathnames
>>> from pathlib import Path
>>> cur_path = Path()
>>> print(cur_path.joinpath('bin','utils','disktools'))
bin/utils/disktools
>>>
>>>
>>> a_path = Path('bin','utils','disktools')
>>> a_path
PosixPath('bin/utils/disktools')
>>>
>>> a_path.parts
('bin', 'utils', 'disktools')
>>>
>>> a_path.name
'disktools'
>>> a_path.parent
PosixPath('bin/utils')
>>> a_path.suffix
''
>>>
>>> b_path = Path('/bin/utils/disktools/pic.jpg')
>>>
>>> b_path.suffix
'.jpg'
>>>
os.path and pathlib.Path Compare
os.pathpathlib.Pathos.path.join('bin','utils','disktools')a_path = Path('bin','utils','disktools')
return <class 'pathlib.PosixPath'>
os.path.split('/bin/utils/disktools/')
return tuple
a_path.parts
return tuple
os.path.dirname('/bin/utils/disktools/')
return str
a_path.parent
return <class 'pathlib.PosixPath'>
os.path.basename('/bin/utils/disktools')
return str
a_path.name
return str
os.path.splitext('/bin/utils/disktools/pic.jpg')
return str
a_path.suffix
return str
12.2.6 Common variables and functions
The most basic constant is os.curdir and os.pardir, The path symbols used by the operating system to represent the directory and the parent directory are defined respectively .
os.name majority Windows Versions are recognized as 'nt'
Running OS X Of Mac On the machine , as well as Linux/UNIX In the system , The return value will be posix
>>> os.curdir
'.'
>>> os.pardir
'..'
>>> os.name
'posix'
>>>
12.3 Get file information
The following function receives path information , return True/False
os.path.exists
os.path.isfile
os.path.isdir
os.path.islink
os.path.ismount
os.path.isabs Is it an absolute path
os.path.samefile(path1, path2) If and only if two paths in the parameter point to the same file , Will return True
os.path.getsize(path) Return the pathname size
os.path.getmtime(path) Last modified
os.path.getatime(path) Last access time
12.4 Other operations of file system
(1)os.listdir Get the list of files in the directory
explain :Python stay os.listdir In the returned file list , It doesn't contain os.curdir and os.pardir identifier
stay glob In the module there is a glob Function can extend Linux/UNIX shell Style wildcards and character sequences , Return the matching files in the current working directory .“*” Will match any sequence of characters ,“?” Match any single character , Character sequence ( Such as [h,H] or [0-9]) Will match any single character in the sequence :
>>> import glob
>>> glob.glob("*.cfg")
['original-ks.cfg', 'anaconda-ks.cfg']
>>> glob.glob("sole?.tst")
['sole1.tst', 'sole2.tst']
>>>
(2) use os.rename You can rename / Move files or directories
(3) use os.remove You can delete files
use os.rmdir You can delete an empty directory
If you want to delete a non empty directory , Please use shutil.rmtree function , It can recursively delete all files in the directory tree
Add :shutil Module copytree function , It can recursively copy all files in the directory and its subdirectories , File permissions and status information ( By visiting / Modification time ) All reserved .
>>> os.rmdir('testdir/1/2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 39] Directory not empty: 'testdir/1/2'
>>>
>>> import shutil
>>> shutil.rmtree('testdir')
>>>
(4) use os.makedirs or os.mkdir Create directory
explain :os.makedirs Will be created together with the necessary intermediate directories , but os.mkdir Can't
pathlib Other file operations provided
(1) Most of the operations mentioned above ,Path Objects have the same function , But there are still some differences .iterdir Method Be similar to os.path.listdir function , but The path iterator is returned Instead of a list of strings
>>> new_path = Path('/opt')
>>> new_path.iterdir()
<generator object Path.iterdir at 0x7f520bf3e820>
>>> list(new_path.iterdir())
[PosixPath('/opt/rh'), PosixPath('/opt/containerd'), PosixPath('/opt/cni')]
>>>
(2) use Path Object's rename Method , You can rename ( Move ) Files and directories
>>> new_path = Path('mymath_update.py')
>>> old_path = Path('mymath.py')
>>> old_path.rename(new_path)
PosixPath('mymath_update.py')
>>>
>>> cur_path = Path('./')
>>> list(cur_path.iterdir())
[PosixPath('addlinenum.py'), PosixPath('drop2hash.py'), PosixPath('linestatistics.py'), PosixPath('replace.py'), PosixPath('mymath_update.py')]
>>>
(3) To remove or delete a data file , Please use unlink Method , Out-of-service unlink Method to delete the directory
To delete a directory, use rmdir Method , It only deletes empty directories
>>> new_path
PosixPath('mymath_update.py')
>>> new_path.unlink()
>>> list(cur_path.iterdir())
[PosixPath('addlinenum.py'), PosixPath('drop2hash.py'), PosixPath('linestatistics.py'), PosixPath('replace.py')]
>>>
(4) To pass the path Object to create a directory , Please use path Object's mkdir Method . If you call with parents=True Parameters ,mkdir Method will create the necessary intermediate directories . otherwise , When the intermediate directory does not exist FileNotFoundError
>>> new_path = Path('/root/newdir1/newdir2/')
>>> new_path.mkdir()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/python3/lib/python3.9/pathlib.py", line 1313, in mkdir
self._accessor.mkdir(self, mode)
FileNotFoundError: [Errno 2] No such file or directory: '/root/newdir1/newdir2'
>>>
>>> new_path.mkdir(parents=True)
[[email protected] ~]# ls -ld /root/newdir1/newdir2/
drwxr-xr-x 2 root root 6 Jul 3 17:43 /root/newdir1/newdir2/
[[email protected] ~]#
13.1 Open the file and file object
open Will not read the contents of the file , It is Return to one file object , It can be used to access the opened file .file Object will track the file and its read / write location .
First call readline Will return file The first line of the object , Including the first line break .
13.2 Close file
>>> file_object = open("myfile", 'r')
>>> line = file_object.readline()
>>> file_object.close()
Use context manager and with keyword :
>>> with open("myfile", 'r') as file_object:
... line = file_object.readline()
... print(line)
...
2022-7-3
>>>
13.4 Functions for reading and writing text and binary data
readline Will be taken from file Object to read and return a row of data , Including line breaks at the end of the line . If there is no data readable in the file ,readline Will return an empty string
【 example 1】 Use readline Calculate the number of text lines in the text file
file_object = open("myfile",'r')
count = 0
while file_object.readline() != "":
count = count + 1
print(count)
file_object.close()
readlines Method will read all lines in the file , And return as a string list ( The newline character at the end of each line remains )
【 example 2】 Use readline Calculate the number of text lines in the text file
file_object = open("myfile",'r')
print(len(file_object.readlines()))
file_object.close()
Be careful : If you want to count the number of lines for a large file ,readlines Method may cause the computer to run out of memory , Because it will read the whole file into memory at one time .
And readline and readlines The write method corresponding to method is write and writelines.
Be careful , non-existent writeline Method .
write Method will write a string , If the string contains a newline , You can write multiple lines at once .
write Method after writing the parameter string , No line breaks will be output .
writelines The parameter of the method is a string list , Write strings one by one file object , But the newline character will not be written . If the string in the list ends with a newline , Then they will be written in multiple lines , Otherwise, they will be closely linked in the document .
>>> myfile = open("myfilewrite",'w')
>>> myfile.write('Hello')
5
>>> myfile.write('Hello')
5
>>> myfile.write('Hi\nHi\nHi')
8
>>> myfile.writelines(['One','Two','Three'])
>>> myfile.writelines(['1\n','Two\n','Three'])
>>>
-------------------------------------------------
[[email protected] pydir]# ls -l myfilewrite
-rw-r--r-- 1 root root 0 Jul 3 19:24 myfilewrite
[[email protected] pydir]#
-------------------------------------------------
>>> myfile.close()
>>>
-------------------------------------------------
[[email protected] pydir]#
[[email protected] pydir]# ls -l myfilewrite
-rw-r--r-- 1 root root 40 Jul 3 19:26 myfilewrite
[[email protected] pydir]# cat myfilewrite
HelloHelloHi
Hi
HiOneTwoThree1
Two
Three[[email protected] pydir]#
however writelines yes readlines Exact inverse operation of , It can be done to readlines The returned list is directly used writelines, Will write an with readlines Read the same file .
Suppose there is a text file myfile.txt, The following code will create a file named myfilecopy.txt An exact copy of :
>>> input_file = open("myfile.txt", 'r')
>>> lines = input_file.readlines()
>>> input_file.close()
>>> output = open("myfilecopy.txt", 'w')
>>> output.writelines(lines)
>>> output.close()
>>>
13.5 use pathlib Read and write files
use Path Object to read and write text files without opening or closing .
Limit : No use Path Method to append data , Because its write operation will replace all existing data .
>>> from pathlib import Path
>>> p_text = Path('my_text_file')
>>> p_text.write_text('Some contents.')
14
>>> p_text.read_text()
'Some contents.'
>>>