Python basic syntax

Posted by dirty_n4ppy on Thu, 06 Jan 2022 12:12:00 +0100

Basic knowledge

Ensure that the font is normal

#-*- coding: utf-8 -*-

Adding can automatically generate relevant data for future reference

@author:freshman2233
@software:${PRODUCT_NAME}
@file:${NAME}.py
@time:${DATE} ${TIME}

notes

#notes

This is my first python program

print("hello,world")#This is a single line comment

'''
This is a line of comments
 These are two lines of comments
'''

variable

#variable
a=5
print("This is a variable:",a)

t_007="T007"
print(t_007)

This is the variable: 5
T007 

Format output

#Format output
age=18
print("My age is%d year"%age)
print("My name is%s,My nationality is%s"%("Xiao Zhang","China"))

My age is 18
My name is Xiao Zhang and my nationality is China

Special output

#Special output
print("aaa","bbb","ccc")
print("www","baidu","com",sep=".")
print("hello",end="")
print("world",end="\t")
print("python",end="\n")
print("end")

When the print() function specifies that the end parameter is null, the print() function will no longer actively add line breaks. Moreover, there is no space between hello and world

aaa bbb ccc
www.baidu.com
helloworld      python
end

input

#input
password=input("Please input a password")#The default is string type
print("The password you just entered is:",password)

Please enter password 123456
The password you just entered is 123456

Test category

#Test category
a=10
print(type(a))

<class 'int'>

Cast type

#Cast type
a=int("123")
print(type(a))
b=a+100
print(b)

<class 'int'>
223

c=int(input("Enter number"))
print(c)

Enter the number 123456
123456

Conditional judgment

#Conditional judgment
if True:
    print("True")
    print("Answer")
else:
    print("False")
print("end")

True
Answer
end

score=77
if score>=90 and score<=100:
    print("This examination, the grade is A")
elif score>=80 and score<90:
    print("The test grade is B")
else:
    print("This examination, the grade is E")

This exam, grade E

Introduce random number

import random   #Introduce random number
x=random.randint(0,2)   #Random number of 0-2

Circulation

for loop

#for loop
for i in range(5):
    print(i)# 0 1 2 3 4

0
1
2
3
4

for i in range(0,10,3):#From 0 to 10, add 3 each time
    print(i)#0 3 6 9

0
3
6
9

for i in range(-10,-100,-30):
    print(i)#-10 -40 -70 -100

-10
-40
-70

name="chengdu"
for x in name:
    print(x,end="\t")

c       h       e       n       g       d       u        

a=["aa","bb","cc","dd"]
for i in range(len(a)):
    print(i,a[i])

0 aa
1 bb
2 cc
3 dd

while loop

#while Loop 
i=0
while i<5:
    print("The current is the second%d Secondary cycle"%(i+1))
    print("i=%d"%i)
    i+=1

This is the first cycle
i=0
This is the second cycle
i=1
This is the third cycle
i=2
This is the fourth cycle
i=3
This is the fifth cycle
i=4

1-100 summation

#1-100 summation - for
sum=0
for i in range(101):
    sum+=i
print(sum)

#1-100 summation while
n=100
sum=0
counter=1
while counter<=n:
    sum+=counter
    counter+=1
print("1 reach%d The sum of is:%d"%(n,sum))

5050
The sum of 1 to 100 is 5050

Execute else if conditions are not met in while

#Execute else if conditions are not met in while
count=0
while count<5:
    print(count,"Less than 5")
    count+=1
else:
    print(count,"Greater than or equal to 5")

0 less than 5
1 less than 5
2 less than 5
3 less than 5
4 less than 5
5 greater than or equal to 5

break continue pass

#break continue pass
i=0
while i<10:
    i+=1
    print("-"*30)
    if i==5:
        break   #End cycle
    print(i)

------------------------------
1
------------------------------
2
------------------------------
3
------------------------------
4
------------------------------

i=0
while i<10:
    i+=1
    print("-"*30)
    if i==5:
        continue    #End this cycle
    print(i)

------------------------------
1
------------------------------
2
------------------------------
3
------------------------------
4
------------------------------
------------------------------
6
------------------------------
7
------------------------------
8
------------------------------
9
------------------------------
10

homework scissors stone cloth

import random   #Introduce random number
x=random.randint(0,2)   #Random number of 0-2

print("Scissors 0 stone 1 cloth 2")
while True:
    try:
        user=int(input("Your input is:"))
        print("Randomly generated number is:%d"%x)
    except ValueError:
        print("Man,learn to type a number")
        continue
    break

if x==user:
    print("it ends in a draw")
elif (x==0 and user==1)or(x==1 and user==2)or(x==2 and user==0):
    print("User wins")
else:
    print("Computer win")

Scissors 0 stone 1 cloth 2
Your input is: 1
Randomly generated number: 1
it ends in a draw

Home 99 multiplication table

#99 multiplication table - for
for i in range(1,10,1):
    for j in range(1,10,1):
        if i<j:
            break
        print("%d*%d=%d"%(i,j,i*j),end="\t")
        if i==j:
            print("\n")

1*1=1

2*1=2   2*2=4

3*1=3   3*2=6   3*3=9

4*1=4   4*2=8   4*3=12  4*4=16

5*1=5   5*2=10  5*3=15  5*4=20  5*5=25

6*1=6   6*2=12  6*3=18  6*4=24  6*5=30  6*6=36

7*1=7   7*2=14  7*3=21  7*4=28  7*5=35  7*6=42  7*7=49

8*1=8   8*2=16  8*3=24  8*4=32  8*5=40  8*6=48  8*7=56  8*8=64

9*1=9   9*2=18  9*3=27  9*4=36  9*5=45  9*6=54  9*7=63  9*8=72  9*9=81

#while
i=1
j=1
n=9
while i<=n:
    j=1
    while j<=n:
        if i<j:
            break
        print("%d*%d=%d"%(i,j,i*j),end="\t")
        if i==j:
            print("\n")
        j+=1
    i+=1

1*1=1

2*1=2   2*2=4

3*1=3   3*2=6   3*3=9

4*1=4   4*2=8   4*3=12  4*4=16

5*1=5   5*2=10  5*3=15  5*4=20  5*5=25

6*1=6   6*2=12  6*3=18  6*4=24  6*5=30  6*6=36

7*1=7   7*2=14  7*3=21  7*4=28  7*5=35  7*6=42  7*7=49

8*1=8   8*2=16  8*3=24  8*4=32  8*5=40  8*6=48  8*7=56  8*8=64

9*1=9   9*2=18  9*3=27  9*4=36  9*5=45  9*6=54  9*7=63  9*8=72  9*9=81

character string

#character string
word='character string'
sentence="This is an orange"
paragraph="""
This is a paragraph
 Can consist of multiple lines
"""

print(word)
print(sentence)
print(paragraph)

character string

This is an orange

This is a paragraph

Can consist of multiple lines


'and' difference (need to use escape character \)

#'and' difference (need to use escape character \)
my_str="I'm a student"
print(my_str)
my_str='I\'m a student'
print(my_str)
my_str="Jason said\"I like you\""
print(my_str)
my_str='Jason said"I like you"'
print(my_str)

I'm a student
I'm a student
Jason said"I like you"
Jason said"I like you"

String interception [start position (obtained): end position (not obtained): step value]

#String interception [start position (obtained): end position (not obtained): step value]
str="chengdu"
print(str)
print(str[0])   #c
print(str[0:5]) #cheng
print(str[1:7:2])   #hnd
print(str[:5])  #cheng
print(str[5:])  #du

chengdu
c
cheng
hnd
cheng
du

String connection

#String connection
print(str+",Hello")    #Hello, chengdu
print(str*3)    #chengduchengduchengdu

Use the transfer character and use r to directly display the original string, so that all the transfer characters will be invalidated

#Use the transfer character and use r to directly display the original string, so that all the transfer characters will be invalidated
print("hello\nchengdu") #hello
                        #chengdu
print(r"hello\nchengdu")    #hello\nchengdu

hello
chengdu
hello\nchengdu

List list

  • List can complete the data structure implementation of most collection classes.
  • The types of elements in the list can be different. It supports numbers, and strings can even contain lists (so-called nesting).
  • The list is a comma separated list of elements written between [].
  • The list index value starts with 0 and - 1 is the starting position from the end.
  • The list can be spliced with the + operator, and * indicates repetition.

Definition and printing of list

#Definition and printing of list
namelist=[] #Define an empty list
 
namelist=["Xiao Zhang","Xiao Wang","petty thief"]
print(namelist[0])
print(namelist[1])
print(namelist[2])

Xiao Zhang
Xiao Wang
petty thief

Lists can store mixed types

testlist=[1,"test"]    #Lists can store mixed types
print(testlist[0])
print(testlist[1])
print(type(testlist[0]))    #<class 'int'>
print(type(testlist[1]))    #<class 'str'>

1
test
<class 'int'>
<class 'str'>

Traversal list

namelist=["Xiao Zhang","Xiao Wang","petty thief"]
for name in namelist:
    print(name)

Xiao Zhang
Xiao Wang
petty thief

len() can get the length of the list

namelist=["Xiao Zhang","Xiao Wang","petty thief"]
print(len(namelist))    #len() can get the length of the list
length=len(namelist)
i=0
while i<length:
    print(namelist[i])
    i+=1

3
Xiao Zhang
Xiao Wang
petty thief

Addition, deletion, modification and query of list

Add: [append] append an element at the end

#Add: [append] append an element at the end
namelist=["Xiao Zhang","Xiao Wang","petty thief"]
print("-----List data before adding")
for name in namelist:
    print(name)
 
nametemp=input("Please enter the name of the added student:")
namelist.append(nametemp)   #Append an element to the end
 
print("-----After adding, the data of the list")
for name in namelist:
    print(name)

-----List data before adding
Xiao Zhang
Xiao Wang
petty thief
Please enter the name of the added student: chicken
-----After adding, the data of the list
Xiao Zhang
Xiao Wang
petty thief
chick

Add: [extend] add each element in the b list to the a list one by one

#Add: [extend]
a=[1,2]
b=[3,4]
a.append(b) #Treat the list as an element and add it to the a list
print(a)    #[1, 2, [3, 4]]
 
a.extend(b) #Add each element in the b list to the a list one by one
print(a)    #[1, 2, [3, 4], 3, 4]

[1, 2, [3, 4]]
[1, 2, [3, 4], 3, 4]

Add: [insert] the first variable represents the subscript and the second variable represents the object element

#Add: [insert]
a=[0,1,2]
a.insert(1,3)   #The first variable represents the subscript and the second variable represents the object element
print(a)    #[0, 3, 1, 2]

[0, 3, 1, 2]

Delete [del] deletes an element at a specified location

#Delete [del] [pop]
 
movieName=["Pirates of the Caribbean","Hacker empire","First Blood","Lord of the rings","Fast & Furious","Lord of the rings"]
 
print("-----Data in the list before deletion")
for name in movieName:
    print(name)
 
del movieName[2]    #Deletes an element at the specified location

print("-----After deletion, the data in the list")
for name in movieName:
    print(name)

-----Data in the list before deletion
Pirates of the Caribbean
Hacker empire
First Blood
Lord of the rings
Fast & Furious
Lord of the rings
-----After deletion, the data in the list
Pirates of the Caribbean
Hacker empire
Lord of the rings
Fast & Furious
Lord of the rings

Delete the last element at the end of the pop-up [pop]

movieName=["Pirates of the Caribbean","Hacker empire","First Blood","Lord of the rings","Fast & Furious","Lord of the rings"]
 
print("-----Data in the list before deletion")
for name in movieName:
    print(name)
 
movieName.pop() #Pop up the last element at the end

print("-----After deletion, the data in the list")
for name in movieName:
    print(name)

-----Data in the list before deletion
Pirates of the Caribbean
Hacker empire
First Blood
Lord of the rings
Fast & Furious
Lord of the rings
-----After deletion, the data in the list
Pirates of the Caribbean
Hacker empire
First Blood
Lord of the rings
Fast & Furious

Delete remove directly deletes the first element of the specified content

movieName=["Pirates of the Caribbean","Hacker empire","First Blood","Lord of the rings","Fast & Furious","Lord of the rings"]
 
print("-----Data in the list before deletion")
for name in movieName:
    print(name)

movieName.remove("Lord of the rings") #Directly delete the first element of the specified content

print("-----After deletion, the data in the list")
for name in movieName:
    print(name)

-----Data in the list before deletion
Pirates of the Caribbean
Hacker empire
First Blood
Lord of the rings
Fast & Furious
Lord of the rings
-----After deletion, the data in the list
Pirates of the Caribbean
Hacker empire
First Blood
Fast & Furious
Lord of the rings

Modify: modify the content of the specified subscript

#change
namelist=["Xiao Zhang","Xiao Wang","petty thief"]
print("-----List data before adding")
for name in namelist:
    print(name)
 
namelist[1]="Xiao Hong"    #Modify the contents of the specified subscript
 
print("-----After adding, the data of the list")
for name in namelist:
    print(name)

Check: [in, not in]

#Check: [in, not in]
namelist=["Xiao Zhang","Xiao Wang","petty thief"]
findName=input("Please enter the name of the student you want to find:")
if findName in namelist:
    print("The same name was found in the list of colleges")
else:
    print("Can't find")

Please enter the name of the student you want to find: Xiao Li
The same name was found in the list of colleges

Find the element index, count of the specified subscript range

#Finds the element of the specified subscript range
mylist=["a","b","c","a","b"]
 
print(mylist.index("a",1,4)) #You can find the element of the specified subscript range and return the subscript of the corresponding data
 
#print(mylist.index("a",1,3))#Range section, left closed right open [1, 3)
                       #An error will be reported if it is not found: exception: 'a' is not in list
print(mylist.count("c"))  #Count how many times an element appears

3
1

Sort: reverse reverses all elements of the list / sort ascending or descending

#sort
a=[1,4,2,3]
print(a)
a.reverse() #Invert all elements of the list
print(a)
 
a.sort()    #Ascending order
print(a)
 
a.sort(reverse=True)    #Descending order
print(a)

[1, 4, 2, 3]
[3, 2, 4, 1]
[1, 2, 3, 4]
[4, 3, 2, 1]

Multidimensional array

#Multidimensional array
schoolNames=[[],[],[]]  #There is an empty list of 3 elements, and each element is an empty list
schoolName=[["Peking University","Tsinghua University"],["Nankai University","Tianjin University","Tianjin Normal University"],["Shandong University"]]
print(schoolName[0][0])

Peking University

homework-8 people were randomly divided into 3 offices

#Eight people were randomly assigned to three offices
import random
office=[[],[],[]]
names=["A","B","C","D","E","F","G","H"]
for name in names:
    index=random.randint(0,2)
    office[index].append(name)
 
i=1
for office in office:
    print("office%d The number of people:%d"%(i,len(office)))
    i+=1
    for name in office:
        print("%s"%name,end="\t")
    print("\n")
    print("-"*20)

Number of people in office 1: 4
A       B       D       E

--------------------
Number of people in office 2: 3
F       G       H

--------------------
The number of people in office 3 is: 1
C

--------------------

Home shopping cart simulation

#Shopping cart simulation
products=[["iphone",6888],["MacPro",14800],["Millet 6",2499],["Coffee",31],["Book",60],["Nike",699]]
 
print("-"*6+" Product list "+"-"*6)
 
for line in range(5):
    print("%d %s       %d"%(line,products[line][0],products[line][1]))
 
buycar=[]
while True:
    num=input("Please enter the item number you want to buy(Exit, please enter q): ")
    if num=="q":
        break
    buy=[int(num)]
    buy.extend(products[int(num)])
    print("Your current purchase is:")
    print(buy)
    buycar.append(buy)
    print("Your shopping cart has:")
    print(buycar)
    print("-"*20)
    print("\n")
 
print("The list of products you purchased is:")
print("-"*6+" Product list "+"-"*6)
 
for i in range(len(buycar)):
    #print(type(i))
    print("%d %s       %d"%(buycar[i][0],buycar[i][1],buycar[i][2]))
    sum=0
    for j in range(len(buycar)):
        sum+=buycar[j][2]
print("The total number of items is:%d\t The total amount is%d"%(len(buycar),sum))

------Product list------
0 iphone       6888
1 MacPro       14800
2 Xiaomi 6 # 2499
3 Coffee       31
4 Book       60
Please enter the item number you want to buy (please enter Q to exit): 0
Your current purchase is:
[0, 'iphone', 6888]
Your shopping cart has:
[[0, 'iphone', 6888]]
--------------------


Please enter the item number you want to buy (please enter Q to exit): 1
Your current purchase is:
[1, 'MacPro', 14800]
Your shopping cart has:
[[0, 'iphone', 6888], [1, 'MacPro', 14800]]
--------------------


Please enter the item number you want to buy (please enter Q to exit): 2
Your current purchase is:
[2, 'Xiaomi 6', 2499]
Your shopping cart has:
[[0, 'iphone', 6888], [1, 'MacPro', 14800], [2, 'Xiaomi 6', 2499]]
--------------------


Please enter the item number you want to buy (please enter Q to exit): 4
Your current purchase is:
[4, 'Book', 60]
Your shopping cart has:
[[0, 'iphone', 6888], [1, 'MacPro', 14800], [2, 'Xiaomi 6', 2499], [4, 'Book', 60]]
--------------------


Please enter the item number you want to buy (please enter q to exit): q
The list of products you purchased is:
------Product list------
0 iphone       6888
1 MacPro       14800
2 Xiaomi 6 # 2499
4 Book       60
The total number of items is: 4. The total amount is 24247

function

Definition of function

def printinfo():
    print("---------------------")
    print("Life is short, I use it python")
    print("---------------------")

Function call

def printinfo():
    print("---------------------")
    print("Life is short, I use it python")
    print("---------------------")
printinfo()

---------------------
Life is short. I use python
---------------------

Type of function

Functions with parameters

def add2Num(a,b):
    c=a+b
    print(c)
 
add2Num(11,22)

33

Parameter with return value

#Parameter with return value
def add2Num(a,b):
    return a+b  #Return the running result through return
 
result=add2Num(11,22)
print(result)
print(add2Num(11,22))

33
33

Function that returns multiple values

#Function that returns multiple values
def divid(a,b):
    shang=a//b
    yushu=a%b
    return shang,yushu  #Multiple return values are separated by commas
 
sh,yu=divid(5,2)
 
print("Business:%d,remainder:%d"%(sh,yu))

Quotient: 2, remainder: 1

Classroom exercises:

1. Write a function that prints a horizontal line. (Note: the horizontal line is composed of several "-")

2. Write a function to print the horizontal line of user-defined lines through the input parameters. (tip: call the above function)

3. Write a function to find the sum of three numbers

4. Write a function to find the average of three numbers (hint: call the above function)

[within 5 minutes for each question]

My answer:

#myself
#First question
def line():
    print("-"*20)
line()

--------------------

#Second question
def line():
    print("-"*20)
def severalLine(a):
    for i in range(a):
        line()
 
a=int(input("Please enter the number of lines to print:"))
severalLine(a)

Please enter the number of lines to print: 5
--------------------
--------------------
--------------------
--------------------
--------------------

#Question 3
def ThreeNumSum(a,b,c):
    return a+b+c
a=int(input("Please enter the first number:"))
b=int(input("Please enter the second number:"))
c=int(input("Please enter the 3rd number:"))
sum=ThreeNumSum(a,b,c)
print("3 The sum of the numbers is%d"%sum)

Please enter the first number: 15
Please enter the second number: 25
Please enter the third number: 35
The sum of the three numbers is 75

#Question 4
def ThreeNumSum(a,b,c):
    return a+b+c
a=int(input("Please enter the first number:"))
b=int(input("Please enter the second number:"))
c=int(input("Please enter the 3rd number:"))
average=ThreeNumSum(a,b,c)/3
print("3 The average number is%d"%average)

Please enter the first number: 15
Please enter the second number: 25
Please enter the third number: 35
The average of the three numbers is 25

Standard answer:

#teacher
#First question
#Print a line
def printOneLine():
    print("-"*30)
#Second question
#Print several lines
def printNumLine(num):
    i=0
    while i<num:
        printOneLine()
        i+=1
#Question 3
#Find the sum of three numbers
def sum3Number(a,b,c):
    return a+b+c
#Question 4
#Complete the average calculation of 3 numbers
def average3Number(a,b,c):
    sumResult=sum3Number(10,20,30)
    aveResult=sumResult/3.0
    return aveResult
 
result=average3Number(10,20,30)
print("The average value is:%d"%result)

Local and global variables

local variable

#Local and global variables
#local variable
def test1():
    a=300   #local variable
    print("test1----Before modification:a=%d"%a)
    a=100
    print("test1----After modification:a=%d"%a)
 
def test2():
    a=500   #Different functions can define the same name, independent of each other
    print("test2----Before modification:a=%d"%a)
 
test1()
test2()

test1 --- before modification: a=300
test1 --- modified: a=100
test2 --- before modification: a=500

global variable

#global variable
a=100   #global variable
 
def test1():
    print("a=%d"%a)
 
def test2():
    print("a=%d"%a)
 
test1()
test2()

a=100
a=100

Global variables have the same name as local variables

#Global variables have the same name as local variables
 
def test1():
    a=300   #local variable
    print("test1----Before modification:a=%d"%a)
    a=200
    print("test1----After modification:a=%d"%a)
 
def test2():
    print("test2----a=%d"%a)    #There are no local variables. Global variables are used by default
 
test1()
test2()

test1 --- before modification: a=300
test1 --- modified: a=200
test2----a=500

Global variables can be changed in functions

#Changing global variables in functions
a=100
def test1():
    global a    #Declare the identifier of the global variable in the function
    print("test1----Before modification:a=%d"%a)
    a=200
    print("test1----After modification:a=%d"%a)
 
def test2():
    print("test2----a=%d"%a)    #There are no local variables. Global variables are used by default
 
test1()
test2()

test1 --- before modification: a=100
test1 --- modified: a=200
test2----a=200

File operation

Open file

#Open file
f=open("test.txt","w")  #w mode (write mode), create a new file if the file does not exist

Write string

#Open file
f=open("test.txt","w")
#Write string
f.write("hello world,i am here!")   #Write string to file

Close file

#Open file
f=open("test.txt","w")

#Write string
f.write("hello world,i am here!")

#Close file
f.close()

Access content

  • r open the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
  • w open a file for writing only. If the file already exists, overwrite it. If the file does not exist, create a new file.
  • A opens a file for appending. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
  • rb opens a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode.
  • wb opens a file in binary format for writing only. If the file already exists, overwrite it. If the file does not exist, create a new file.
  • ab opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing. r + open a file for reading and writing. The file pointer will be placed at the beginning of the file.

The read method reads the specified characters. At the beginning, the pointer is at the file head. Each execution moves the specified number of characters backward

Test under the project file directory Txt file content is

hello world,i am here!--1
hello world,i am here!--2
hello world,i am here!--3
hello world,i am here!--4
hello world,i am here!--5

#The read method reads the specified characters. At the beginning, the pointer is at the file head. Each execution moves the specified number of characters backward
f=open("test.txt","r")

content=f.read(5)

print(content)

content=f.read(10)

print(content)

f.close()

hello
 world,i a

readlines reads all files at once as a list, with one string element per line

#Read all files at one time as a list, one string element per line
f=open("test.txt","r")

content=f.readlines()

print(content)

['hello world,i am here!--1\n', 'hello world,i am here!--2\n', 'hello world,i am here!--3\n', 'hello world,i am here!--4\n', 'hello world,i am here!--5']

#Read all files at one time as a list, one string element per line
f=open("test.txt","r")

content=f.readlines()

#print(content)

i=1
for temp in content:
    print("%d:%s"%(i,temp))
    i+=1

f.close()

1:hello world,i am here!--1

2:hello world,i am here!--2

3:hello world,i am here!--3

4:hello world,i am here!--4

5:hello world,i am here!--5

readline reads one line at a time

#readline reads one line at a time
f=open("test.txt","r")

content=f.readline()
print("1:%s"%content)

content=f.readline()
print("2:%s"%content)

f.close()

1:hello world,i am here!--1

2:hello world,i am here!--2

File related operations

Sometimes, you need to rename and delete files. This function is available in the os module of python. 5.3.1

Rename file rename

rename() in the os module can rename files. Rename (file name to be modified, new file name)

import os
os.rename("test.txt","test1.txt")

test.txt renamed test1 txt

remove delete file

remove() in the os module can delete files. Remove (file name to be deleted)

import os
os.remove("test.txt")

mkdir create folder

import os
os.mkdir("Zhang San")

getcwd get the current directory

import os
os.getcwd()
print ("Current working directory:%s" % os.getcwd())

Current working directory: C: \ users \ 93983 \ source \ repos \ 0106 Python basic syntax

chdir change default directory

import os

path = "C:/Users/93983/source/repos/0106-python Basic grammar/Zhang San"

# View current working directory
retval = os.getcwd()
print ("Current working directory is %s" % retval)

# Modify current working directory
os.chdir( path )

# View the modified working directory
retval = os.getcwd()

print ("Directory modified successfully %s" % retval)

The current working directory is C: \ users \ 93983 \ source \ repos \ 0106 Python basic syntax
Directory modification succeeded. C: \ users \ 93983 \ source \ repos \ 0106 Python basic syntax \ Zhang San

listdir get directory list

import os
os.listdir("./")

Current working directory: ['. Vs',' 0106 Python basic syntax. Pyproj ',' 0106 Python basic syntax. SLN ',' test. TXT ',' 0106 Python basic syntax. py ',' Zhang San ']

rmdir delete folder

import os
os.rmdir("Zhang San")

Errors and exceptions

Catch exception

try:
    print("-----test----1")
    f=open("123.txt","r")   #Open a nonexistent file in read-only mode and an error is reported
    print("-----test----2") #This code will not execute


except IOError: #The file is not found, which belongs to IO exception (input / output exception)
    pass    #Code executed after an exception is caught

-----test----1

The exception type is consistent

try:
    print(num)
#except IOError:    #Exception types need to be consistent in order to be caught
except NameError:
    print("An error occurred")

An error occurred

Get error type

try:
    print("-----test----1")
    f=open("123.txt","r")   #Open a nonexistent file in read-only mode and an error is reported
    print("-----test----2")

    print(num)

except (NameError,IOError) as result: #Put all exception types generated by Ken in the following parentheses
    print("An error occurred")
    print(result)

-----test----1
An error occurred
[Errno 2] No such file or directory: '123.txt'

Catch all exceptions

try:
    print("-----test----1")
    f=open("123.txt","r")   
    print("-----test----2")

    print(num)
except Exception as result: #Exception can accept any exception
    print("An error occurred")
    print(result)

-----test----1
An error occurred
[Errno 2] No such file or directory: '123.txt'

try finally and nested

test.txt content

abed, I see a silver light,
Suspected ground frost.
look at the bright moon,
Bow your head and think of your hometown.

import time
try:
    f=open("test.txt","r")

    try:
        while True:
            content=f.readline()
            if len(content)==0:
                break
            time.sleep(2)
            print(content)
    finally:
        f.close()
        print("File close")

except Exception as result:
    print("exception occurred")
finally:
    print("End of file")

File close
exception occurred
End of file

Error reason: Unicode decoding error: Message ='gbk 'codec can't decode byte 0x80 in position 36: illegal multibyte sequence

Solution: add one after encoding='UTF-8 '.

import time
try:
    f=open("test.txt","r",encoding='UTF-8')

    try:
        while True:
            content=f.readline()
            if len(content)==0:
                break
            time.sleep(2)
            print(content)
    finally:
        f.close()
        print("File close")

except Exception as result:
    print("exception occurred")
finally:
    print("End of file")

abed, I see a silver light,

Suspected ground frost.

look at the bright moon,

Bow your head and think of your hometown.
File close
End of file

Homework: Ancient Poetry

1. Apply the relevant knowledge of file operation and create a new file gushi.com through Python Txt, select an ancient poem and write it to the file

⒉. Write another function to read the specified file Gushi Txt, copy the contents to copy Txt and output "copy completed" on the console.

3. Prompt: define two functions respectively to complete the operation of reading and writing files

Improve the code as much as possible and add exception handling.

Write ancient poetry

#Write ancient poetry
import os
f=open("gushi.txt","w")
f.write("abed, I see a silver light,\r Suspected ground frost.\r look at the bright moon,\r Bow your head and think of your hometown.")
f.close()
\nEnter with the cursor on the next line
\rWrap, cursor on previous line

gushi.txt

abed, I see a silver light,
Suspected ground frost.
look at the bright moon,
Bow your head and think of your hometown.

Copy ancient poetry

#Write ancient poetry
import os
f=open("gushi.txt","w")
f.write("abed, I see a silver light,\r Suspected ground frost.\r look at the bright moon,\r Bow your head and think of your hometown.")
f.close()

#Copy ancient poetry
f=open("copy.txt","w")
g=open("gushi.txt","r")

content=g.readlines()

for temp in content:
  f.write("%s"%temp)
    
g.close()
f.close()
    
print("copy complete")

copy complete

copy.txt

abed, I see a silver light,
Suspected ground frost.
look at the bright moon,
Bow your head and think of your hometown.

Reading ancient poetry

#Write ancient poetry
import os
f=open("gushi.txt","w")
f.write("abed, I see a silver light,\r Suspected ground frost.\r look at the bright moon,\r Bow your head and think of your hometown.")
f.close()


#Reading ancient poetry
def readGushi(Name):
  f=open("%s"%Name,"r")
  content=f.readlines()

  for temp in content:
    print("%s"%temp,end="")
  f.close()

Name=input("Please enter the name of the file you want to open:\n")
readGushi(Name)

Please enter the name of the file you want to open:
gushi.txt
abed, I see a silver light,
Suspected ground frost.
look at the bright moon,
Bow your head and think of your hometown.

Write ancient poetry

#Reading ancient poetry
def readGushi(Name):
  f=open("%s"%Name,"r")
  content=f.readlines()

  for temp in content:
    print("%s"%temp,end="")
  f.close()

#Write ancient poetry
def writeGushi(Name,content):
    f=open("%s"%Name,"w")
    f.write("%s"%content)
    f.close()

Name=input("Please enter the file name (including suffix) of the ancient poem you want to create:\n")
content=input(r"Please enter ancient poetry:")
writeGushi(Name,content)
readGushi(Name)

Please enter the file name (including suffix) of the ancient poem you want to create:
123.txt
Please enter ancient poetry: 123456
123,456

Topics: Python Back-end