Python beginners Summary 3: files, collections, functions, variables, etc,
I. File Operations:
File Operation Process:
1. open the file, get the file handle, and assign it to a variable.
2. Operate the file through a handle
3. close the file
File opening modes include:
- R, read-only mode (default ).
- W, write-only mode. [Unreadable; created if no data exists; deleted if data exists ;]
- A. append mode. [Readable; created if it does not exist; appended content if it exists ;]
"+" Indicates that a file can be read and written simultaneously.
- R +, which can read and write files. [Readable; writable; appendable]
- W +, write and read
- A +, same as
"U" indicates that \ r \ n can be automatically converted to \ n (used in the same mode as r or r +) during read)
"B" indicates processing binary files (for example, sending and uploading ISO image files via FTP, which can be ignored in linux and must be noted when processing binary files in windows)
Original file yesterday2:
(1) reading files
F = open ("yesterday2", 'R', encoding = "UTF-8") # file handle. 'R' is the Read mode. If it is not written, the default value is 'R ', 'W' is used to create a file, and the original file is gone.
Data2 = f. read ()
Print ('------ data2 ------ \ n', data2)
Execution result:
(2) for Loop File Reading
For I in range (3 ):
Print (f. readline () # Read one row each time and read three rows in total
For line in f. readlines ():
Print (line. strip () # strip () removes spaces and line breaks
The original file yesterday2 before running:
Execution result:
(3) Writing files
F = open ("yesterday2", 'w', encoding = "UTF-8 ")
F. write ("black heart \ n") # 'W' write creates a file, and the content of the original file is gone.
F. write ("why wocould you offer more \ n ")
F. write ("Why wocould you make it easier on me to satisfy ")
Execution result:
(4)
F = open ("yesterday2", 'R', encoding = "UTF-8 ")
Print (f. readlines () # each row is a list of elements ['black black heart \ n', 'Why wocould you offer more \ n ', 'Why wocould you make it easier on me to satisfy ']
(5)
F. readlines () is only suitable for reading small files, because the memory is fully read once loaded during reading.
So you can use a loop to read a row and delete a row, and save only one row in the memory to process large files:
Count = 0
F = open ("yesterday", 'R', encoding = "UTF-8 ")
For line in f:
If count = 4:
Print ('---------- I am a split line -------')
Count + = 1
Pass
Print (line. strip ())
Count + = 1
F. close ()
Execution result:
Figure (5)-1
NOTE: If "pass" in the above Code is rewritten to "continue", the execution result is as follows:
Figure (5)-2
Compared with figure (5)-1 and figure (5)-2, we found that the latter was missing: "If you call your friends and nobody's home. if you call a friend but no one is at home, this is because the execution mechanism of pass is different from that of continue. When count = 4 is set, the following print (line. strip (), and after continue, the program jumps to if count = 4:, so a row is printed less.
(6) read and write r +
F = open ("yesterday2", 'r + ', encoding = "UTF-8") # read/write
Print (f. readline ())
Print (f. readline ())
Print (f. readline ())
Print (f. tell ())
F. write ("\ n ------- add one line ----------- \ n") # At the end of the file
Print (f. readline ())
Execution result:
The original file becomes:
(7) binary file read rb
F = open ("yesterday2", 'rb') # Binary File Read
Print (f. readline ())
Print (f. readline ())
Print (f. readline ())
Execution result:
(8) modifying files
"Create a new file when modifying the file. The modified file appears in the new file """
F = open ("yesterday2", "r", encoding = "UTF-8 ")
F_new = open ("yesterday2.bak", "w", encoding = "UTF-8 ")
For line in f:
If "experienced a storm and endured loneliness" in line:
Line = line. replace ("the storm has endured the loneliness", "The storm has endured the loneliness ")
F_new.write (line)
F. close ()
F_new. close ()
After the execution, a new file yesterday2.bak is created:
(9) With statement: automatically close the file after execution
Syntax:
With open ("yesterday2", "r", encoding = "UTF-8") as f ,\
Open ("yesterday2", "r", encoding = "UTF-8") as f2:
Python specification: a single line of code should not exceed 80 characters, so you can use "\" to open multiple files and write multiple lines
2. progress bar Applet:
Import sys, time
For I in range (20 ):
Sys. stdout. write ("#")
Sys. stdout. flush ()
Time. sleep (0.1)
Iii. Set
List_1 = [1, 2, 5, 3, 2, 6, 4, 2, 6]
List_1 = set (list_1) # converts a list into a set, and the set is unordered and not repeated.
List_2 = set ([2, 5, 3, 22, 1])
Print (list_1, list_2) # {1, 2, 3, 4, 5, 6} {33, 2, 1, 5, 22}
Print (list_1, type (list_1) # {1, 2, 3, 4, 5, 6} <class 'set'>
# Intersection
Print (list_1. intersection (list_2) # = print (list_1 & list_2) # {1, 2, 5}
# Union
Print (list_1. union (list_2) # = print (list_1 | list_2) # {1, 2, 3, 4, 5, 6, 33, 22}
# Difference set
Print (list_1. difference (list_2) # = print (list_1-list_2) # {3, 4, 6}
# Subset
List_3 = set ([1, 2, 5])
Print (list_3. issubset (list_2) # True
# Symmetric difference set. The two sets are retrieved from each other.
Print (list_1. symmetric_difference (list_2) # = list_1 ^ list_2 # {33, 3, 4, 22, 6}
List_3 = set ([1, 2, 5])
List_4 = set ([4, 6, 8])
Print (list_3. isdisjoint (list_4) # returns True if there is no intersection between list_3 and list_4 # True
List_1. add (889) # add an item
List_1. update ([123,234,345]) # add multiple entries, = list_1. update ({123,234,345 })
Print (list_1) # {1, 2, 3, 4, 5, 6,345,234,889,123}
Iv. Local variables and global variables
Names = ["Lili", "Vae", "Cici"]
Def change_name ():
Names [0] = "Li" # list, set, and dictionary can be changed to global variables in the local area. (The tuples cannot be changed, and the strings and integers cannot be changed)
Print ("inside func", names)
Change_name ()
Print ("outside func", names)
Execution result:
Inside func ['lily', 'vae', 'cii']
Outside func ['lily', 'vae', 'cii']
V. Example of a Higher-Order Function
Def add (a, B, f ):
Return f (a) + f (B)
Res = add (3,-6, abs) # abs: Return the absolute value of the argument.
Print (res) #9
6. A Recursive example
Def calc (n ):
Print (n)
If int (n/2) = 0:
Return n
Return calc (int (n/2 ))
Calc (10) #10 5 2 1
VII,
1. functions and processes
# Functions
Def func1 ():
"Testing1, This is a function """
Print ('IN the func1 ')
Return 0
# A process is a function without return values.
Def func2 ():
'''Testing2, this is a process '''
Print ('IN the func2 ')
X = func1 () # output: in the func1
Y = func2 () # output: in the func1
Print ('from func1 return is % s' % x) # output from func1 return is 0
Print ('from func1 return is % s' % y) # output: from func1 return is None
2. function call
Import time
Def logger ():
Time_format = '% Y-% m-% d % x' # format: year, month, day, hour, minute, second
Time_current = time. strftime (time_format) # Convert a time tuple to a string according to a format specification.
With open('a.txt ', 'a +') as f:
F. write ('% s end action \ n' % time_current)
Def test1 ():
Print ('test1 starting action ...')
Logger ()
Test1 () # test1 starting action...
Create a new file a.txt at the same time:
3. function return value:
Def test1 ():
Print ('IN the test1 ')
Def test2 ():
Print ('IN the test2 ')
Return 0
Def test3 ():
Print ('IN the test3 ')
Return 1, 'Hello', ['bob', 'lili'], {'name': 'bob '}
Y = test2 ()
Z = test3 ()
Print (test1 () # None
Print (y) #0
Print (z) # (1, 'Hello', ['bob', 'lili'], {'name': 'bob'}) when return is more than one, return one tuples.
4. Default function parameters
# Default parameter features: When a function is called, default parameters are not required
Purpose: 1: def test (x, soft1 = True, soft2 = True). When the default installation value is set to True, soft1 is installed by default.
2: connect to the database: def conn (host, port = 3301)
Pass
Host default port number
(1)
Def test (x, y = 2 ):
Print (x)
Print (y)
Test (1, y = 3) #1 3
(2) parameter groups
1def test (* args ):
Print (args)
Test (,) # (1, 2, 3, 4, 5, 4) when the real parameters are not fixed, put the accepted real parameters into the tuples.
Test (* [1, 2, 3, 4, 5]) # (1, 2, 3, 4, 5) that is: args = tuple ([1, 2, 3, 4, 5])
2def test1 (x, * args ):
Print (x)
Print (args)
Test1 (, 7) #1)
3 # ** kwargs converts n keyword parameters into dictionaries. key: value, key: value...
Def test2 (** kwargs ):
Print (kwargs)
# Print (kwargs ['name'])
# Print (kwargs ['age'])
# Print (kwargs ['sex'])
Test2 (name = 'lili', age = 22, sex = 'y') # {'name': 'lili', 'age': 22, 'sex ': 'y '}
Test2 (** {'name': 'vae', 'age': 31, 'sex': 'y'}) # {'name': 'lili ', 'age': 22}
The output results are as follows:
A {'name': 'lili', 'age': 22, 'sex': 'y'} {'name': 'vae', 'age': 31, 'sex': 'y '}
Blili vae
C22 31
DY Y
Def test3 (name, ** kwargs ):
Print (name)
Print (kwargs)
Test3 ('cecila ', age = 22, sex = 'y ')
Output: cecila {'age': 22, 'sex': 'y '}
# * Args: receives N location parameters and converts them to a metagroup. ** kwargs receives keyword parameters and converts them to a dictionary.
Def test5 (name, age = 22, * args, ** kwargs ):
Print (name) # vae
Print (age) #31
Print (args) # output :()
Print (kwargs) # {'sex': 'y', 'hobby': 'book '}
Test5 ('vae', sex = 'y', holobby = 'book', age = 31)