Python note 11 file

catalogue

file

Open file

File reading

Close file

File write

with statement

Summary:

Practical operation

file

Common file types:


 

f = open("C:/Users/reach/Desktop/record.txt", "r", encoding="utf-8") #Open file
content = f.read()  #Read file contents
f.close()      #Close file
print(content)  #Test file

Open file

The open () function opens the file and returns the file object

We use the built-in function open() to open the file test Txt, and then use the variable f to store the open file

The open() function receives three parameters, the first is the file path, the second is the file read-write mode, and the third is the file decoding method. For the first two parameters, we use positional parameters, passing in "test.txt" and "r" respectively. For the last parameter, we use keyword parameters..

f = open("C:/Users/reach/Desktop/record.txt", "r", encoding="utf-8") #Open file

The formal parameters corresponding to the three arguments are file, mode and encoding. File indicates the file path to read and write, which is a string type; Mode is a read-write mode and a string type; Encoding is a decoding method and a string type.

Then let's look at the second formal parameter mode, which passes in "r", which means that we need to process the file in a read-only way.

What does read-only mean? Read only means that you can only read, not write. "r" is the abbreviation of the English word read, which represents the read-only mode. "r" is also the default value of the mode parameter.

In other words, if we do not pass in an argument to the formal parameter mode, the open() function will also use the read-only processing mode by default.

File reading

f.read() reads the contents of the file F. The read () function is a unique method of a file object and has no parameters.

We store the contents read from the file to the variable content, and print out the content variable at the end.

content = f.read()  #Read file contents
f.close()      #Close file
print(content)  #Test file

  • The readline() method reads data line by line,
  • The readlines() method reads the data of all lines of the entire file at one time. The data lines are distinguished by \ n
  • list(f) can put the whole content of the file into the list
  • tell() can tell you where the current pointer is

 

Close file

Simple and rough, don't forget

Variable name.close()

File write

f = open("C:/Users/reach/Desktop/record.txt", "w", encoding="utf-8")  # Open file
# Step 2 write content
f.write('one two three four five\n')
f.write('Go up the mountain to fight the tiger\n')
# Step 3 close the file
f.close()
# Part IV open file in read-only mode
f = open("C:/Users/reach/Desktop/record.txt", "r", encoding="utf-8")
date = f.read()
f.close()
print(date)

Write mode is used here, which is "w".

Different from "r" which means read-only, "w" is the abbreviation of write, which means write only. Therefore, when writing, the parameter value passed in to the parameter mode should be "w"

When writing, all contents of the file will be emptied first, and then write from the first line. If you don't want to overwrite the original content, you can use another mode "a" (append) to append

f = open("C:/Users/reach/Desktop/record.txt", "a", encoding="utf-8")  # Open file
# Step 2 write content
f.write('one two three four five\n')
f.write('Go up the mountain to fight the tiger\n')
# Step 3 close the file
f.close()
# Part IV open file in read-only mode
f = open("C:/Users/reach/Desktop/record.txt", "r", encoding="utf-8")
date = f.read()
f.close()
print(date)

with statement

with open("C:/Users/reach/Desktop/record.txt", "a", encoding="utf-8") as f:
    f.write("Here is with Sentences written in sentences")

Instead of closing the file with close (), the sentences written by the with statement are saved

Summary:

 

Practical operation

Write a program that accepts user input and saves it as a new file

def file_write(file_name):
    f = open(file_name, "w",encoding="utf-8")
    print("Please enter the content. If you enter it separately w Save and exit")

    while True:
        write_some = input()
        if write_some != 'w':
            f.write(write_some)
        else:
            break
    f.close()


file_name = input("Please enter a file name:")
file_write(file_name)


Write a program to print the first N lines of the file to the screen when the user enters the file name and number of lines (N)

def file_view(file_name, line_num):
    print('%s Document%s The line reads as follows' % (file_name, line_num))
    f = open(file_name,encoding="utf-8")
    for i in range(int(line_num)):
        print(f.readline(), end='')

    f.close()


file_name = input('Please enter a file name:')
line_num = input('Please enter the number of rows:')
file_view(file_name, line_num)

Keywords: Python Back-end

Added by ghostdog74 on Tue, 14 Dec 2021 14:24:27 +0200