Article 10 learning content

Posted by Liz_SA on Thu, 03 Mar 2022 05:27:49 +0100




#Three steps for writing text files
#1. Create file object
#2. Write data
#3. Close file object
f=open("a.txt","a")##"A" stands for mode. If we do not add mode b, the object created by default is a text file object
s="Shang Xuetang\n Baizhan programmer\n"
f.write(s)
f.close()##Be sure to close this action


English can be implemented directly. For a small part of Chinese, the solution to Chinese garbled code will be explained separately below

Relationship between common codes:




The code and short code should be consistent

f=open(r"b.txt","w")#The code defaults to GBK, but UTF8 is used when it is opened, so it is garbled when it is opened
f.write("Shang Xuetang\n Baizhan programmer\n")##\n means line break
f.close()##Be sure to close this action

When solving Chinese garbled code, change it to GBK format for unification

close() closes the file stream

ry :
    f=open(r"b.txt","w")
    strs=("aa\n","bbb\n")#Reference multiple strings, so str becomes strs
    f.writelines(strs)
except BaseException as e:
    print(e)
finally:
    f.close()##Be sure to close this action



Derived generation list:
You want to add line numbers to the three lines in the file. How to modify the contents of the list?

A new function to solve this problem, enumerate(), function: enumerate objects

You can see the object of enumerate() here.



Therefore, the final code is as follows:
Replace the temp with line

Reading and writing of binary files

aa.gif is a picture. Read the content of the picture and copy the file







import csv module


Reader reader; Writer writer
b_csv.writerows() rows is the writing of multi row list, and row is the input line by line



dir is the directory


Note that print(os.sep) is a backslash in windows and a / forward slash in the other two systems.

Supplement the above stat function

Create multi-level directory




Supplement:
Create directory

In Python, you can use OS The mkdir() function creates a directory (creates a first level directory).

Its prototype is as follows:

os.mkdir(path)

The parameter path is the path of the directory to be created.

For example, you want to create a directory of hello under disk D

>>> import os

>>> os.mkdir('d:\hello')

You can use OS The makedirs() function creates a multi-level directory.

Its prototype is as follows:

os.makedirs(path)

The parameter path is the path of the directory to be created.

For example, create a directory of books under disk D, and create a directory of books under the directory of books

>>> import os

>>>os.makedirs('d:\books\book')

Delete directory

In Python, you can use OS The rmdir() function deletes the directory.

Its prototype is as follows:

os.rmdir(path)

The parameter path is the path of the directory to be deleted.

For example, delete the directory of hmm under disk D

>>> import os

>>> os.rmdir('d:\hmm')

Delete multilevel directory

In Python, you can use OS The removediers() function deletes multi-level directories.

Its prototype is as follows:

os.removdirs(path)

The parameter path is the path of the multi-level directory to be deleted.

>>> import os

>>> os.removedirs('d:\books\book')

#Note: the directory to be deleted must be empty

... \ usage


os.path module

os,os. How to use the commonly used functions about files and directories in the path module

See the link for specific table contents

#coding =utf-8
#Test the operation of directory / path in OS and path
import  os
import os.path  #Same usage as from os import path
print (os.path.isabs("d:/a.txt"))# Judge whether the specified path is an absolute path. true
print (os.path.isdir("d:/a.txt"))#Judge whether the specified path exists and is a directory. false
print (os.path.isfile("d:/a.txt"))# Judge whether the specified path exists and is a file true
print (os.path.exists("d:/a.txt"))# Judge whether the specified path (directory or file) exists true

Expand the usage of some functions related to obtaining the basic information of the file: see the link for the specific function name and meaning

#coding=utf-8
#List all Py files in the working directory and output the file name
import os
path=os.getcwd() ##getcwd() returns the current working directory
file_list=os.listdir(path)#List subdirectories and sub files
for filename in file_list: #Traverse all sub files
    print (filename) # Output file name


Switch() function
Description: determines whether a string ends with a specified character or substring.

import os
path=os.getcwd()
file_list=os.listdir(path)#List subdirectories and sub files
for filename in file_list: #Traverse all sub files
    if filename.endswith("py"): #Judge whether the string ends with the specified character or substring. Here, judge whether it ends with py
    print (filename) # Output file name

os.walk() – recursively traverses all files


After traversing all folders and files

import os
path=os.getcwd()
list_files=os.walk(path)
for diepath,dirnames,filenames in list_files:
    for dir in dirnames: #Traverse folders only
        print(dir)
    for file in filenames: #Traverse only files
        print(file)


import os
all_files=[]
path=os.getcwd()
list_files=os.walk(path)
for dirpath,dirnames,filenames in list_files:
    for dir in dirnames: #Traverse folders only
        all_files.append(os.path.join(dirpath,dir))

    for file in filenames: #Traverse only files
        all_files.append(os.path.join(dirpath, file))
for file in all_files:
    print(file)

Supplementary learning for os module: shutil() function

shutil module of Python module



zipfile() - > compression


w write mode, r mode
extractall() extract

Recursive algorithm;

#Use recursion to calculate the factorial of n. generally speaking, recursion can also be handled with loops
def factorial(n):#Defining a factorial variable as n factorials starts with a large number and ends with 1
    if n == 1: ##In the comparison structure, the assignment should use==
        return n
    else:
        return n*factorial(n-1)
print(factorial(5))#Calculate 5!


_ Principle of recursive algorithm_ Directory tree structure display

Topics: Python