Reading and writing of files in python (1)

It's really crashing. The notes I just wrote are wrong, and now I have to rewrite them again. Crash. . . . . . . . . .

I won't repeat the nonsense before, let's go straight to the topic.

Today, Xiao R took a one-day NP course, but I still can't forget python, so I learned to read and write files again in the evening, so let's share some experience now. 

Before speaking, let's talk about the principle of reading and writing files:

The functions of reading and writing files on the disk are provided by the operating system. Modern operating systems do not allow ordinary programs to directly operate the disk, so reading and writing is to request the operating system to open a file object (usually called a file descriptor), and then pass The interface provided by the operating system reads data from this file object (read file), or writes data to this file object (write file)

File operation process:

1. Open the file, get the file handle and assign it to a variable.

2. Operate the file through the handle

3. Close the file

eg:

Now if there is a file with the name 'test', there are some text such as lyrics in it.

Want to open it and some actions:

f = open ('test', 'r' ,encoding = 'utf-8')

Explanation: 'test' file name 'r' is in read mode ('w' is naturally in write mode) encoding Needless to say, encoding means.

first_line = f.readline()  

print('first_line:', first_line) # read a line

data = r.read() # Read the rest of the content, do not use it when the file is large

print (data) # do not explain

f.close() #Close the file

There are several ways to open a file:

① r, read-only mode (default)

② w, write-only mode (unreadable: create if it does not exist; delete the content if it exists)

③ a, Add mode. (Readable; create if it doesn't exist, just append if it exists)

I'll wait for tomorrow, Xiao R is a little tired today and has to exercise. Continue learning tomorrow.

Guess you like

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