python basic tutorial

Keywords: Python encoding Programming ascii

Python basic tutorial

I. Introduction

1.1 introduction to Python

Founder of python: Guido Van Rossum
Python download address: https://www.python.org/
Python document download address: https://www.python.org/doc/
Pycharm download address: https://www.runoob.com/w3cnote/pycharm-windows-install.html
Download address of Linux Installation Package: https://www.python.org/downloads/source/

1.2 Python2 vs python 3

(1) Python 3. X supports Chinese by default
(2) python3.X is not compatible with python2.X
(3) Python 3. X core syntax adjustment, easier to learn
(4) The new feature is only available on Python 3. X by default

1.3 introduction to programming language

Programming languages are classified from the following perspectives: compiled, static, dynamic, strongly typed and weakly typed

1.3.1 compiled type:

There is a program responsible for translation to transform our source code and generate the corresponding executable code. This process is compilation, and the program responsible for compilation is called Compiler

1.3.2 dynamic type:

It refers to the language used for data type checking during operation. That is to say, when programming in a dynamically typed language, you never need to assign a data type to any variable. The language will record the data type internally when you assign it to a variable for the first time. Typically python and Ruby

1.3.3 static type:

The data type is checked during compilation, that is, the data type of all variables should be declared when writing the program. C/C + + is a typical representative of static type language. Other static type languages include C and JAVA

1.4 what kind of language is Python

Python is a high-level scripting language that combines interpretability, compilation, interactivity and object-oriented.
Python design has a strong readability, compared with other languages often use English keywords, some punctuation symbols of other languages, it has a more distinctive syntax structure than other languages.

1.4.1 explanatory language

This means that there is no compilation in the development process. Similar to PHP and Perl

1.4.2 interactive language

This means that you can execute the code directly after a Python prompt.

1.4.3 object oriented language

This means that Python supports object-oriented style or code encapsulation in object programming techniques.

1.4.4 language for beginners

Python is a great language for junior programmers. It supports a wide range of application development, from simple word processing to WWW browsers to games.

1.5 what can Python do

Network applications, scientific computing, GUI programs, system management tools, others, etc

1.6 python features

1.6.1 characteristics

(1) Easy to learn: Python has relatively few keywords, simple results, and a clearly defined syntax, making learning easier
(2) Easy to read: a clearer definition of Python code
(3) Easy to maintain: Python's success is that its source code is fairly maintainable
(4) A wide range of standard libraries: one of the biggest advantages of Python is its rich libraries, cross platform, and good compatibility in Unix, Windows and macintosh
(5) Interactive mode: support of interactive mode, you can input the language of executing code and obtaining results from the terminal, interactive test and debugging code fragments
(6) Portability: Based on its open source nature, Python has been ported (that is, made to work) to many platforms
(7) Extensible: if you need a fast key code or you want to write some algorithms that do not want to be open, you can use C or C++ to complete that part of the program, and then call it in your Python program.
(8) Databases: Python provides interfaces to all major commercial databases
(9)GUI Programming: Python supports GUI creation and migration to many system calls
(10) Embeddable: you can embed Python into C/C + + programs, so that users of your programs can get the ability of "scripting"

1.6.2 advantages

Simple, high development efficiency, high-level language, portability, scalability, embeddable

1.6.3 drawback

Slow, but relative, code cannot be encrypted, threads cannot use multiple CPU s

1.7 python interpreter

Cpython,IPython,PyPy,Jython,IronPython

Two, installation

Linux, windows, pycharm installation

Three. Introduction

3.1 character encoding

When the python interpreter loads the code in the. py file, it encodes the content (the default is ASCII).
ASCII (American Standard Code for Information Interchange) is a set of computer coding system based on Latin alphabet, which is mainly used to display modern English and other Western European languages. It can only be represented by 8 bits at most (one byte), that is, 2 * * 8 = 256. Therefore, ASCII code can only represent 256 symbols at most.
Obviously ASCII code can't represent all kinds of characters and symbols in the world, so we need a new code that can represent all characters and symbols, that is, Unicode.
**
Unicode (unified code, universal code, single code) is a kind of character encoding used in computer.
**Unicode is generated to solve the limitations of traditional character encoding schemes. It sets a unified and unique binary encoding for each character in each language. It stipulates that although some characters and symbols are represented by at least 16 bits (2 bytes), that is, 2 * * 16 = 65536,
Note: Here we are talking about at least 2 bytes, maybe more.
UTF-8 is the compression and optimization of Unicode code. Instead of using at least 2 bytes, it classifies all characters and symbols: ascii code is saved with 1 byte, European characters are saved with 2 bytes, and East Asian characters are saved with 3 bytes
python2.x version, the character code supported by default is ASCll, python3.x version, and Unicode is supported by default, which can directly display Chinese without declaring character code

3.2 notes

Single line comment: single line comment
Multiline comment: (1) multiline comment or multiline comment

3.3 key words

python has some special function identifiers, which are so-called keywords
The keyword is already used by python, so developers are not allowed to define the identifier with the same name as the keyword

and     as      assert     break     class      continue    def     del
elif    else    except     exec      finally    for         from    global
if      in      import     is        lambda     not         or      pass
print   raise   return     try       while      with        yield

You can view keywords in the following ways

import keyword
print(keyword.kwlist)

3.4 format output

age = 22
print('I am this year%d year'%age)
Result: I'm 22 years old

3.4.2 common formatted output

3.5 variable

Python has only variables and no constants;
All uppercase is constant, but value can still be modified, just uppercase to represent constant.

3.5.1 naming rules of variables

(1) To be descriptive
(2) Variable names can only be any combination of letters, numbers or underscores, and can't be spaces or special characters (×? <, $¥ *! ~)
(3) Cannot use Chinese as variable name
(4) Cannot start with a number or a space
(5) Cannot start with an uppercase letter (all uppercase letters represent constants in python)
(6) Reserved characters (keywords) cannot be declared as variable names

3.5.2 definition of variables

(1) Each variable is created in memory, including the identification, name and data of the variable;
(2) Each variable must be assigned before use, and it will be created only after it is assigned;
(3) The equal sign (=) is used to assign values to variables;
(4) To the left of the equal sign (=) operator is a variable name, and to the right of the equal sign (=) operator is the value stored in the variable

3.5.3 variable memory release

There is a garbage collection mechanism in Python. After a period of time, the variables that are no longer used will be cleared automatically. It does not need to be cleared manually. Of course, it can also be cleared manually. If the variables are cleared manually, they will be cleared. However, the python garbage collection mechanism points the unused variables to another variable.

3.5.4 variable type

Variable types include variable assignment, multiple variable assignment, standard data type, python number, Python string, python list, python tuple, python dictionary, and python data type conversion.

3.5.4.1 variable assignment

Variable assignments in Python do not require type declarations.
Each variable is created in memory and includes information such as the identification, name and data of the variable.
Each variable must be assigned a value before it can be used. The variable will not be created until it is assigned a value.
The equal sign (=) is used to assign values to variables.
To the left of the equal sign (=) operator is a variable name, and to the right of the equal sign (=) operator is the value stored in the variable.
For example:

Example Result
counter = 100 ×× assign integer variable
miles = 1000.0 × floating point
name = "John" ා string
Print(counter) 100
Print(miles) 1000.0
Print(name) John
3.5.4.2 assignment of multiple variables

Python allows you to assign values to multiple variables at the same time. For example:

a = b = c = 1

In the above example, an integer object with a value of 1 is created, and three variables are allocated to the same memory space.
You can also specify multiple variables for multiple objects. For example:

a, b, c = 1, 2, "john"

In the above example, two integer objects 1 and 2 are assigned to variables a and b respectively, and string object "john" is assigned to variable c.

3.5.4.3 standard data type

There are many types of data stored in memory.
For example, a person's age can be stored in numbers, and his name can be stored in characters.
Python defines standard types for storing various types of data.
Python has five standard data types:

  • Numbers
  • String (string)
  • List (list)
  • Tuple (tuple)
  • Dictionary (Dictionary)
3.5.4.4 python number

Python supports four different number types:

  • int (signed integer)
  • Long (long [can also represent octal and hexadecimal])
  • float (floating point)
  • complex
int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEl 32.3e+18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2E-12 4.53e-7j
  • Long integers can also use lowercase L, but it is recommended that you use uppercase l to avoid confusion with the number 1. Python uses l to display long integers.
  • Python also supports complex numbers, which are composed of real part and virtual part. They can be represented by a + bj or complex(a,b). Both real part a and virtual part B of complex numbers are floating-point types.
Be careful
	 long type only exists in Python version 2. X,
	 In versions later than 2.2, int type data will be automatically converted to long type after overflow;
	 In Python 3. X, the long type was removed and replaced with int.
3.5.4.5 python string

python's string list has two values:

  • The left to right index starts from 0 by default, and the maximum range is 1 less than the string length
  • Right to left index starts with - 1 by default, and the maximum range is at the beginning of the string

If you want to get a segment of substring from a string, you can use [header subscript: Trailer subscript] to intercept the corresponding string, where the subscript is calculated from 0, can be positive or negative, and the subscript can be empty to indicate that the header or tail is taken.
[head subscript: tail subscript] the substring obtained contains the characters of the head subscript, but does not contain the characters of the tail subscript.
When you use a colon delimited string, python returns a new object with the result containing the continuous content identified by the offset pair, starting with the lower boundary.
The above result contains the value b of s[1], while the maximum range obtained does not include the suffix, that is, the value f of s[5].
The plus sign (+) is a string concatenation operator and the asterisk (*) is a repeat operation. Here is an example:

Python list truncation can receive the third parameter. The parameter function is the step size of truncation. The following example intercepts the string at the position from index 1 to index 4 and sets the step size to 2 (one position apart):

Common ways

str = 'abcdef'
print(str[1:5])  # Get value according to subscript
print(Str[1:-5]) # Get value according to subscript
print(str) # Output full string 
print(str[0]) # First character in output string 
print(str[2:5]) # String between the third and sixth of the output string
print(str[2:]) # Output a string starting with the third character 
print(str + "TEST") # Output concatenated string
print(Str[1:4:2]) # Output the first to fourth characters in steps of 2

print('hello' * 2) # Print string twice
print('helloWorld'[2:]) # Get value according to subscript
print('lll' in 'helloWorld') # Determine whether a value exists in a string
print('lll' in ['helloWorld', 12, 'lll']) # Determine whether a value exists in a list
print('%s is a good teacher!!!'%'allure') # Format output% s

# String splicing
a = '111'
b = '222'
d = 'abc'
c = a + b # Method 1
print(c)  

c = ''.join([a, b, d]) # Method two
print(c)

String built in method

str = "hello kitty {name} age is {age} years"
# print(str.count('l')) # View the number of an element in str
# print(str.capitalize()) # Capitalize the first letter of a string
# print(str.center(50, '-')) # Center string
# print(str.endswith('y')) # True or false print (str.endswitch ('y ', 10, 11)) is returned when the judgment ends with the content of a string
# print(str.startswith('h', 0, 1)) # Judgment starts with a string content and returns true or false print (str.startswitch ('h '))
# print(str.expandtabs(tabsize=10)) # str = "he\tllo kitty" set the space, which is usually used by '\ t'
# print(str.find('t')) # Finds the first element and returns its index value
# print(str.format(name = 'allure', age = '24')) # Format the output with common expressions, and configure str = "hello kitty {name} age is {age} years" to use
# print(str.format_map({'name': 'allure', 'age': '24'})) # Format the output with common expressions, and configure str = "hello kitty {name} age is {age} years" to use
# print(str.index('t')) # Equivalent to str.find('t '), if no error is found, find will not return - 1
# print(str.isdigit()) # Determine if str is an integer
# print(str.isalnum()) # Determine if str is a string containing numbers and letters
# print('B13445579880011001'.isdecimal()) # Determine if str is a decimal number
# print(str.isnumeric()) # Same as isdigit, no difference
# print('12adf'.isidentifier()) # Determine if str is an illegal variable
# print(str.islower()) # Determine whether str is all lowercase
# print(str.isupper()) # Determine if str is all uppercase
# print(str.isspace()) # Determine if str is a space
# print('Hello Kitty'.istitle()) # To determine whether str is a title, the initial of each word must be uppercase
# print(''.join(['12', '34', '56'])) # String splicing
# print(str.lower()) # Change all uppercase characters to lowercase
# print(str.upper()) # Change all lowercase characters to uppercase
# print(str.swapcase()) # Reverse case of letters
# print(str.ljust(50, '*')) # Place placeholder to the right
# print(str.rjust(50, '*')) # Place placeholder on left
# print(' dfa afd adsf    \n'.strip()) # Replace the spaces (', \ t and \ n) on both sides of the string
# print(' dfa afd adsf    \n'.ltrip()) # Replace the spaces (', \ t, and \ n) to the left of the string
# print(' dfa afd adsf    \n'.rtrip()) # Replace the spaces (', \ t, and \ n) to the right of the string
# print('afsda'.replace('a', '123', 1)) # Replace a string with what you want to replace, parameter 1: what to replace, parameter 2: what to replace, parameter 3: how many values to replace
# print('a b c d e f'.split(' ')) # Separate
# print(str.rsplit('i')) # From right to left, start to separate, only once
# print(str.title()) # Convert string to Title Format

# Consolidate lists into strings
a = ['a', 'b', 'c', 'd', 'e', 'f']
print(''.join(a))

Common String built-in functions

# print(str.count('l')) # View the number of an element in str
# print(str.capitalize()) # Capitalize the first letter of a string
# print(str.center(50, '-')) # Center string
# print(str.endswith('y')) # True or false print (str.endswitch ('y ', 10, 11)) is returned when the judgment ends with the content of a string
# print(str.startswith('h', 0, 1)) # Judgment starts with a string content and returns true or false print (str.startswitch ('h '))
# print(str.find('t')) # Finds the first element and returns its index value
# print(str.format(name = 'allure', age = '24')) # Format the output with common expressions, and configure str = "hello kitty {name} age is {age} years" to use
# print(str.index('t')) # Equivalent to str.find('t '), if no error is found, find will not return - 1
# print(str.isdigit()) # Determine if str is an integer
# print(str.isalnum()) # Determine if str is a string containing numbers and letters
# print(str.lower()) # Change all uppercase characters to lowercase
# print(str.upper()) # Change all lowercase characters to uppercase
# print('a b c d e f'.split(' ')) # Separate
# print('afsda'.replace('a', '123', 1)) # Replace a string with what you want to replace, parameter 1: what to replace, parameter 2: what to replace, parameter 3: how many values to replace
# print(' dfa afd adsf    \n'.strip()) # Replace the spaces (', \ t and \ n) on both sides of the string
3.5.4.6 python list

List is the most frequently used data type in Python.
List can complete the data structure implementation of most collection classes. It supports characters, numbers, strings and even lists (that is, nesting).
The list is identified by [], which is the most common composite data type of python.
The cutting of the value in the list can also use the variable [head subscript: tail subscript], which can intercept the corresponding list. From the left to the right index, the default value is 0, and from the right to the left index, the default value is - 1. If the subscript is empty, the head or tail will be taken.

code details:

	D:\code\PycharmProjects\pythonProject\pythonBase\list.py
3.5.4.7 python tuple

Tuples are another data type, similar to lists.
Tuples are identified with (). Internal elements are separated by commas. However, tuples cannot be assigned twice, which is equivalent to a read-only list.

tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 ) 
tinytuple = (123, 'john')
print(tuple)      # Output complete tuple 
print(tuple[0])   # First element of output tuple 
print(tuple[1:3]) # Output the second to fourth (not included) elements 
print(tuple[2:])  # Output all elements from the third to the end of the list
print(tuple[0:4:2])# Output elements from the first to the fourth in steps of 2
print(tinytuple * 2)    # Output tuple twice 
print(tuple + tinytuple)    # Print combined tuples
3.5.4.8 python dictionary

Dictionary is the only mapping type in python, which stores data in the form of key value pair. python performs the hash function operation on the key, and determines the storage address of value according to the calculation result. Therefore, the dictionary is unordered and the key must be hashable. Hashable indicates that the key must be of immutable type, such as number, string, tuple.
Dictionary is the most flexible type of built-in data structure in python except list. A list is an ordered combination of objects, and a dictionary is an unordered collection of objects.
The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.
The dictionary is identified by "{}". A dictionary consists of an index (key) and its corresponding value, value.
code details:

	D:\code\PycharmProjects\pythonProject\pythonBase\Dictionaries.py

Create dictionary

# Creation method 1
dic = {'name': 'allure', 'age': 23, 'hobby': 'girl', 'sex': 'man'}
print(dic)

dic = {'name': 'allure', 'age': 23, 'hobby': {'girl_name': 'Alice', 'girl_age': 24}, 'sex': 'man'}
print(dic['hobby'])

# Creation method 2
dic2 = dict((('name', 'allure'), ('age', 23)))
print(dic2)

# Creation method 3
dic3 = dict((['name', 'allure'], ['age', 23]))
print(dic3)

# Creation method 3
dic4 = dict([['name', 'allure'], ['age', 23]])
print(dic4)

Corresponding operation
increase

dic1 = {'name': 'allure'}
print(dic1)
# dic1['name'] = 18 # If the key exists, modify it directly, otherwise append
dic1['age'] = 18

# setdefault: the key exists and returns the corresponding value in the dictionary
res1 = dic1.setdefault('age',34) 
print(res1)

# setdefault: the key does not exist. Add a new key value pair in the dictionary and return the corresponding value
res2 = dic1.setdefault('hobby','girl') 
print(res2)

print(dic1)

query

dic = {'name': 'allure', 'age': 23, 'hobby': 'girl', 'sex': 'man'}

# Query all
print(dic)

# Search by key
print(dic['name'])

# Query all keys in the dictionary
print(dic.keys()) # A keys type type(dic.keys) is returned
print(type(dic.keys)) # A dict_keys is returned
print(list(dic.keys())) # Convert dict_keys type to list type

# Query all values in the dictionary
print(dic.values()) # dict_values
print(type(dic.values()))  # Return a dict_values
print(list(dic.values())) # Convert dict_values type to list type

# Query all key value pairs in the dictionary
print(dic.items()) # Returns a key value pair of type dict item

modify

dic = {'name': 'allure', 'age': 23, 'hobby': 'girl', 'sex': 'man'}
print(dic)
dic['name'] = 'Alice'
print(dic)
dic2 = {'name': 'jack', 'age': 55, 'hobby': 'boy', 'sex': 'failman', 'classId': '20200110'}
dic.update(dic2)
print(dic)

delete

dic = {'name': 'allure', 'age': 23, 'hobby': 'girl', 'sex': 'man'}
print(dic)
del dic['name'] # Delete the key value pair specified in the dictionary
print(dic)
dic.clear() # Empty dictionary
print(dic)
dic.pop('age') # Deletes the key value pair specified in the dictionary and returns the value in the key value pair
print(dic)
dic.popitem() # It is useless to delete a group of key value pairs randomly and return values in tuple form
print(dic)
del dic # Delete entire dictionary

Some common other operations and related methods
dict.fromkeys

dic = dict.fromkeys(['host1', 'host2', 'host3'], 'test')
print(dic) # {'host1': 'test', 'host2': 'test', 'host3': 'test'}
dic['host2'] = 'hello'
print(dic) # {'host1': 'test', 'host2': 'hello', 'host3': 'test'}

dic = dict.fromkeys(['host1', 'host2', 'host3'], ['test1', 'test2'])
print(dic) # {'host1': ['test1', 'test2'], 'host2': ['test1', 'test2'], 'host3': ['test1', 'test2']}
dic['host2'] = ['test1', 'test3'] # {'host1': ['test1', 'test2'], 'host2': ['test1', 'test2'], 'host3': ['test1', 'test2']}
dic['host2'][1] = 'test3' # {'host1': ['test1', 'test3'], 'host2': ['test1', 'test3'], 'host3': ['test1', 'test3']}
print(dic)

Dictionary nesting

av_catalog = {
    "Europe and America":{
        "www.youporn.com": ["A lot of free,The world's largest","General quality"],
        "www.pornhub.com": ["A lot of free,Also great","mass ratio yourporn High point"],
        "letmedothistoyou.com": ["Mostly self timer.,Lots of high quality pictures","Not many resources,Slow update"],
        "x-art.com":["The quality is very high.,It's really high.","All charges,Loser, please bypass"]
    },
    "Japan and Korea":{
        "tokyo-hot":["How about the quality,I don't like Japan and South Korea anymore","I heard it's a charge"]
    },
    "Mainland":{
        "1024":["All free,Splendid,A good man is safe all his life","Server is abroad,slow"]
    }
}

av_catalog['Europe and America']['www.youporn.com'][1] = ['Quality HD']
print(av_catalog)

d.copy(): make a shallow copy of dictionary D, and return a new dictionary with the same key value pair as D

# copy(): make a shallow copy of dictionary d, and return a new dictionary with the same key value pair as d
av_catalog_copy = av_catalog.copy()
print(av_catalog_copy)

sorted(dict): returns an ordered list of all key s in the dictionary

dic = {5: '555', 2: '222', 4: '444'}
sort_res1 = sorted(dic.items()) # Sort by key, return key value pair
sort_res2 = sorted(dic.keys()) # Sort by key, return key
sort_res3 = sorted(dic.values()) # Sort by value, return value
print(sort_res1)
print(sort_res2)
print(sort_res3)

Dictionary traversal (three ways to print dictionary through for loop)

# There are three ways to print dictionary through for loop
dic = {'name': 'allure', 'age': 23, 'hobby': 'girl', 'sex': 'man'}
# Highest efficiency
for i in dic:
    print(i, dic[i])

# Low efficiency, with a conversion operation
for i in dic.items():
    print(i)

# Low efficiency, with a conversion operation
for i, v in dic.items():
    print(i, v)

3.9 encoding

For details, see: https://blog.csdn.net/weixin_45775343/article/details/103870743

4, File flow

4.1 document operation

Document preparation

I couldn't help crying last night.
It's three o'clock.
Get up and walk around alone.
People are quiet and the moon is dim outside the curtain.
Bai Shou is famous for his work. The old mountain is full of pines and bamboos.
I want to pay my heart to Yao Qin.
Few bosom friends, who listens to the broken string.

4.1.1 read file

"""
    #Read file
        1. Open file
        2. Read file
        3. Close file
    open: 
        Parameter 1: file name
        Parameter 2: operation name
        Parameter 3: coding format
    read: what is the parameter? read several characters
"""
''''''
file = open('file', 'r', encoding='utf-8')
data = file.read()
print(data)
file.close()

4.1.2 write data

"""
    #Write data file
        1. Open file
        2. Write to file
        3. Close file
    open: 
        Parameter 1: file name
        Parameter 2: operation name
        Parameter 3: coding format
    Write: write in the parameters, clear the file, and write in the data
"""
file = open('file', 'w', encoding='utf-8')
file.write('helloWorld')
file.close()

4.1.3 additional data

"""
    #Append data
        1. Open file
        2, Append data
        3. Close file
    open: 
        Parameter 1: file name
        Parameter 2: operation name
        Parameter 3: coding format
    Write: write in the parameters, clear the file, and write in the data
"""
file = open('file', 'a', encoding='utf-8')
data = file.write("""
I couldn't help crying last night.
It's three o'clock.
Get up and walk around alone.
People are quiet and the moon is dim outside the curtain.
Bai Shou is famous for his work. The old mountain is full of pines and bamboos.
I want to pay my heart to Yao Qin.
Few bosom friends, who listens to the broken string.
""")
print(data)
file.close()

4.1.4 add string at specified place

"""
    # Add a string at the specified place
"""
file = open('file', 'r', encoding='utf-8')
data = file.readlines() # Read out the data and operate later to improve the execution efficiency
file.close()

number = 0
for i in data:
    number += 1
    if number == 6:
        i = ''.join([i.strip() + 'String']) # Replace the evil '+'
    print(i.strip())

4.1.5 read file data, enterprise version**

"""
    Read with readline, so that there will always be only < = 1 row of data in memory, and the execution efficiency will be very high
 enumerate: the returned one has a mapping relationship, and the sequence number can be changed
"""
file = open('file', 'r', encoding='utf-8')
#for i in file: This is an iterator made of file object in for, which takes one line from one line
#     print(i.strip())

for i, v in enumerate(file.readlines()):
    print(i+1, v.strip())

4.1.6 view cursor position

"""
    tell: View cursor position
        3 characters in Chinese
        1 character in English
"""
file = open('file', 'r', encoding='utf-8')
print(file.tell())
print(file.read(10))
print(file.tell())

4.1.7 adjust cursor

"""
    seek: adjust cursor
        3 characters in Chinese
        1 character in English
"""
''''''
file.seek(0)
print(file.tell())
print(file.read(10))
print(file.tell())

4.1.8 flush(): two ways to flush data from memory to disk and progress bar

"""
    flush(): Data in memory flush To disk
    //Commonly used in progress bar
"""
file = open('file1', 'w', encoding='utf-8')
file.write('helloWorld')
file.flush()

"""
    //Progress bar, two ways
"""
# One way
import sys,time
for i in range(30):
    sys.stdout.write('*')
    sys.stdout.flush()
    time.sleep(0.5)

# Mode two
import sys,time
for i in range(30):
    print('*', flush = 'True', end = '')
    time.sleep(0.5)

4.1.9 truncate(): truncate file data

"""
    truncate(): Truncate file data
"""
''''''
file = open('file1', 'a', encoding='utf-8')
file.truncate(7)
file.close()

4.1.10 r+,w+,a + mode

"""
    r+: read-write mode
    w+: Read write mode
    a+: Append read mode
"""

# r +: read write mode, read first, append to the end of the file
file = open('file1', 'r+', encoding='utf-8')
data = file.readline()
file.write('\nhelloWorld')
print(data)
file.close()

# w +: write read mode, delete all before writing
file = open('file1', 'w+', encoding='utf-8')
file.write('helloWorld\n')
print(file.tell())
file.seek(0)
print(file.readline())
file.close()

# a +: append read mode, directly trace to the end of the file
file = open('file1', 'a+', encoding='utf-8')
file.write('helloWorld\n')
print(file.tell())
file.seek(0)
print(file.readline())
file.close()

4.1.11 final question, append a string to the file

'''
    //The ultimate problem is to put a string in the middle of the file
'''
f_read = open('file1', 'r', encoding='utf-8')
f_write = open('file2', 'w', encoding='utf-8')
num = 0
for line in f_read.readlines():
    num += 1
    if num == 6:
        line = ''.join([line.strip(), 'allure\n'])
    f_write.write(line)

f_write.close()
f_read.close()

4.1.12 use with to manage multiple file objects at the same time

'''
    with Use,Manage multiple file objects at the same time
    	//Mode 1 is equivalent to mode 2
'''
# One way
with open('file1', 'r', encoding='utf-8') as file:
    data = file.readlines()
print(data)

# Mode two
file = open('file1', 'r', encoding='utf-8')
data = file.readlines()
print(data)
Published 23 original articles, won praise 0, visited 1428
Private letter follow

Posted by dt_gry on Mon, 13 Jan 2020 23:28:11 -0800