python learning day3

One, python file operation

The basic process of file operation:

The computer system is divided into three parts: computer hardware, operating system, and application program.

If an application program written in python or other languages ​​wants to save the data permanently, it must be saved in the hard disk, which involves the application program operating the hardware. As we all know, the application program cannot directly operate the hardware. to the operating system. The operating system encapsulates complex hardware operations into a simple interface for users/applications to use. The file is the virtual concept provided by the operating system to the application to operate the hard disk. By operating the file, the user or application can permanently save its own data. .

With the concept of files, we no longer need to consider the details of operating the hard disk, but only need to pay attention to the process of operating files:

method one:
#Open the file, get the file handle and assign it to a variable
f = open('D:\code\\1.txt',encoding='utf-8',mode='r') #Specify the open file itself, the default is to open in read mode
file = f.read() #Operate the file through the handle

f.close() #Close the file, the file opened by this method must be closed after the operation is completed, otherwise there will be a risk of memory overflow

Method Two:
#The advantage of this method does not need to worry about closing the file, as long as the code under the with statement is executed, the method will automatically close the file for you
with open('D:\code\st.txt','w') as f: f.write("hello") #absolute path

File opening method:

#1. The modes for opening files are (default is text mode):
 r , read-only mode [default mode, the file must exist, and an exception will be thrown if it does not exist]
w, write-only mode [unreadable; create if it does not exist; clear the content if it exists]
a, append-only write mode [unreadable; if it does not exist, create it; if it exists, only append the content]
Note: It is enough to use the three modes of r, w, and a in normal work. It is not recommended to use modes such as r+ and w+

#2. For non-text files, we can only use b mode, "b" means to operate in bytes (and all files are also stored in bytes, using this mode does not need to consider the characters of the text file encoding, jgp format for picture files, avi format for video files)
rb
wb
away
Note: When opening in b mode, the read content is byte type, and the byte type must also be provided when writing, and the encoding cannot be specified

#3, '+' mode (that is, adding a function)
r+ , read and write [readable, writable] w+ , write and read [writable, readable] a+ , write-read [writable, readable] #4, read-write, write-read, write-read mode operated by bytes type r+ b, read-write [readable, writable] w+ b, write-read [writable, writable] read] a+b, write read [writable, readable]

Common file operation methods:

f1 = open('Flight hostess, nurse, teacher, housewife.txt', encoding='utf-8', mode='r' )
content = f1.read()
print(content)
f1.close()

# read Read all, this method is strongly not recommended, because this method will load all files into memory, if the file is too large, the memory will burst
f1 = open('log1', encoding='utf-8') content = f1.read() # print(content) f1.close()
 #read(n) f1 = open('log1', encoding='utf-8' ) content = f1.read(5) # r mode reads character by character. print (content) f1.close() f1 = open('log1', mode='rb' ) content = f1.read(3) # rb mode reads byte by byte. print(content.decode('utf-8' )) f1.close() #readline() read line by line f1 = open('log1', encoding='utf-8' ) print (f1.readline()) print (f1.readline()) print (f1.readline()) print (f1.readline()) f1.close() #readlines() take each line as an element of a list and return this list f1 = open(' log1', encoding='utf-8' ) print (f1.readlines()) f1.close() #for loop f1 = open('log1', encoding='utf-8' ) for i in f1: print ( i) f1.close() #We recommend using a for loop at work #Additional coding: s1 = b'\xd6\xd0\xb9\xfa') #Convert gbk encoding to utf-8 print(s3) # b'\xe4\xb8\xad\xe5\x9b\xbd' s1 = b'\xd6\xd0\xb9\xfa'.decode('gbk') .encode('utf-8' ) print(s1)

File modification:

1. Open the original file and generate a file handle.
2. Create a new file and generate a file handle.
3. Read the original file, modify it, and write the new file.
4. Delete the original file.
5. Rename the original file to the new file.

# The data of the file is stored on the hard disk, so there is only coverage and no modification. The modified files we usually see are the effects of simulation. Specifically, there are two ways to achieve it: 

Method 1: Load all the contents of the file stored on the hard disk into the memory, which can be modified in the memory. After the modification is completed, the memory is overwritten to the hard disk (word, vim, nodpad ++ and other editors)
 import os   #Call the system module 

with open( ' a.txt ' ) as read_f, open( ' .a.txt.swap ' , ' w ' ) as write_f:
    data =read_f.read() #Read all into memory, if the file is very large, it will be very stuck 
    data=data.replace( ' Tom ' , ' jerry ' ) #Complete the modification in memory 
    write_f.write(data) # One -time Write a new file 
os.remove( ' a.txt ' )   #Delete the original file os.rename 
( ' .a.txt.swap ' , ' a.txt ' )    #Rename the new file to the original file



Method 2: Read the contents of the file stored in the hard disk into the memory line by line, write a new file after the modification, and finally overwrite the source file with the new file
import them

with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
    for line in read_f:
        line=line.replace('Tom','jerry')
        write_f.write(line)

os.remove('a.txt')
os.rename('.a.txt.swap','a.txt') 

 

2. Function

A function is an organized, reusable piece of code that implements a single, or related function .

Functions can improve application modularity and code reuse. You already know that Python provides many built-in functions, such as print(), len(), etc. But you can also create your own functions, which are called user-defined functions.

#function definition 
def mylen ():
     """ Calculate the length of s1 """ 
    s1 = " hello world " 
    length = 0
     for i in s1:
        length = length+1
    print(length)

#function call   mylen 
() #function name +() execute function

#The return value of the function return 
'''
1. When return is encountered, the function ends.
def func1():
print(11)
print(22)
return
print(333)
print(444)
func1()
2. Return a value to the caller (executor) of the function.
no return returns None
return do not write or None return None
return returns a single number.
return returns multiple numbers, and returns multiple numbers in a tuple.
'''

Function parameters:

#Function definition 
def mylen(s1):
     """ Calculate the length of s1 """ 
    length = 0
     for i in s1:
        length = length+1
    return length

#function call str_len 
= mylen( " hello world " )
 print ( ' str_len : %s ' %str_len)

We tell the mylen function who the string is to be calculated. This process is called  passing parameters, referred to as passing parameters. The "hello world" we pass when we call the function and s1 when we define the function are parameters .

actual participation parameter

The parameters are also different:

The "hello world" we pass when we call the function is called the actual parameter, because this is the actual content to be given to the function, called the actual parameter for short .

When defining a function, s1 is just the name of a variable, which is called a formal parameter , because it is just a form when defining a function, indicating that there is a parameter here, referred to as a formal parameter . 

pass multiple parameters

Multiple parameters can be passed, and multiple parameters are separated by commas.

def mymax(x,y):
    the_max = x if x > y else y
    return the_max

ma = mymax (10,20 )
 print (ma)

Dynamic parameters *args, **kwargs universal parameters

 

3. Namespace and scope

Let's recall how a function is encountered when the python code is running.

After starting execution from the python interpreter, a space is opened up in memory

Whenever a variable is encountered, the correspondence between the variable name and the value is recorded.

However , when encountering a function definition, the interpreter only symbolically reads the function name into memory , indicating that it knows the existence of the function. As for the variables and logic inside the function, the interpreter does not care at all.

When the function call is executed, the python interpreter will open up another piece of memory to store the content of the function. At this time, only pay attention to the variables in the function, and the variables in the function will be stored in the newly opened memory. The variables in the function can only be used inside the function, and when the function is executed, all the contents of this memory will be cleared.

Note: We give this "name-value relationship" space a name - it's called the namespace

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324804891&siteId=291194637