say it up front

Python file read and write operations are introduced in the Zhejiang Education Edition textbook by way of extended links, which is not the focus of the exam; however, file operations are an important part of programming, and related codes appear many times in the textbook; the 2022 exam paper The 12th question focuses on the reading and writing operations of text files; the fourth chapter, "Data Processing and Application", requires mastering the reading and writing operations of CSV and Excel files.

Therefore, in teaching, it is very necessary to arrange a class to learn the reading and writing operations of Python text files.


picture


Overall teaching concept :

The content of Python file operation is relatively complex, and there is no need to cover everything in teaching, just introduce key knowledge.

The teaching focuses are: file open mode, basic methods of reading and writing files, including open(), close(), readline() and write(). Other common methods of document objects can provide relevant information and encourage students who have spare capacity to study after class.

Teaching process design:

Introducing a new class: Review the methods of input and output in the IDLE interface.

Task 1. Enter four ancient poems line by line: The bright moonlight in front of the bed is suspected to be frost on the ground. Raise your head to look at the bright moon, and bow your head to think of your hometown. and output line by line. The program works as follows:

picture

Please program the above functions.

Reference Code:

【示例程序1】for i in range(4):    a = input("请输入诗句:")    print(a)

New lesson teaching activity 1: Text file writing operation

Task 2. For long-term preservation of data, data must be stored in a file. The function of the following program is to input four ancient poems line by line and store them in the text file "Ancient Poems.txt". Please read the code to try to understand the meaning of each statement, and run the program to observe the effect of the program execution.

【示例程序2】fp = open("古诗.txt", "w")for i in range(4):    a = input("请输入诗句:")    fp.write(a)fp.close()

The results are as follows:

picture

Knowledge Tips:

1. Python file type

In order to preserve data long-term for reuse, modification, and sharing, data must be stored in the form of files to external storage media or cloud disks. According to the organization of the data in the file, the file can be divided into two categories: text file and binary file.

Text files store regular strings, consisting of several lines of text, each line usually ending with a newline '\n'. Regular strings refer to strings that Notepad or other text editors can display and edit normally and that can be directly read and understood by humans, such as English letters, Chinese characters, and numeric strings.

Binary files store object content as bytes, which cannot be edited directly with Notepad or other ordinary text processing software, and usually cannot be directly read and understood by humans. Special software is required to decode and read, Display, modify or execute. Common ones such as graphic image files, audio and video files, executable files, resource files, and various database files are all binary files.

2. Python file manipulation

Whether it is a text file or a binary file, the operation process is basically the same, that is, first open the file and create a file object, then read, write, delete, modify the file content through the file object, and finally close and Save the file contents.

Python has a built-in file object. Through the open() function, you can open the specified file in the specified mode and create a file object. The syntax is:

open(file,mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Among them, file specifies the name of the file to be opened; mode specifies the file opening mode, such as "read-only", "read-write", "append", etc.; other parameters generally use the default values, and can also be set as needed.

picture

picture

picture

Note: Teachers can provide the above reference materials, but only need to focus on the open(), close() and write() methods involved in the program.

Cognitive conflict: The code structure of sample program 1 and sample program 2 are similar, but the output results are different, that is, print(a) outputs verses line by line, but fp.write(a) writes all verses on the same line .

Task 3. How to modify the sample program 2 to realize the function of writing only one poem per line?

Tip: The string needs to end with a newline character '\n' and write it into a text file to implement the newline function.

Reference Code:

【示例程序3】fp = open("古诗.txt", "w")for i in range(4):    a = input("请输入诗句:")    fp.write(a + "\n")fp.close()

New course teaching activity 2: Text file reading operation

Task 4. Know that an ancient poem is stored in the text file "Ancient Poem.txt", write a program to read the content of the file, and output it to IDLE line by line. Please read the code carefully and complete the missing code.

【示例程序4】fp = open("古诗.txt", 第1空)line = fp.readline()  # 思考readline()的功能是什么while line:    print(line.strip()) # 若改成print(line)会怎样?    line = 第2空第3空

Additional instructions:Python provides a more concise method of reading files line by line, that is, directly using a for loop to traverse a text file line by line. The reference code is as follows:

【示例程序5】fp = open("古诗.txt", "r")for line in fp:    print(line.strip()) fp.close()

New course teaching activity 3: Comprehensive training of text file reading and writing operations

Task 5. The text file "Guanshanyue.txt" stores Li Bai's poem "Guanshanyue". The wind is tens of thousands of miles long, blowing through the Yumen Pass. Han went down Baideng Road, Hu peeped at Qinghai Bay. The origin of the battle, no one has returned. The garrison looked at the border town, thinking about how bitter it was. When the high-rise building is this night, the sigh is not idle. The bright moon rises out of the Tianshan Mountains, among the vast sea of ​​clouds.

This is a piece of text delimited by title, please write a program to convert this text into poetry style with "." as the delimiter, each sentence occupies one line, output line by line (note the period), and overwrite the content of the original file .

The following program can achieve the above functions, please read the code carefully and complete the missing code.

【示例程序6】fp = open('关山月.txt', 'r')text = ""line = fp.readline()while line:    text = text + line.strip()    line =  ①            fp.close()fp = open('关山月.txt', ②          )lines = text.split('。')for line in lines:    if line: # 思考如果不写if语句会出现什么情况?        fp.write(③                   )fp.close()

Supplementary note: The sample program 6 opens the file twice, and performs the read and write operations of the file respectively, which is not efficient. In fact, Python provides a read-write mode, which can be read or written after opening a file. The reference code is as follows:

【示例程序7】fp = open('关山月.txt', 'r+')text = fp.read()   # 一次性读入文件到字符串text中fp.seek(0)       # 将读取指针移动到文件开头lines = text.split('。')for line in lines:    line = line.strip() # 去除多余空行    if line: # 思考如果不写if语句会出现什么情况?        fp.write(line + '。\n')fp.close()

Knowledge Tips:

The file must be closed after use, because the file object will occupy the resources of the operating system, and the number of files that the operating system can open at the same time is limited. In order to prevent programmers from forgetting to close the file, Python introduces the with statement to automatically call the close() method for us:

with open(file,mode) as f:

    dosomething

The keyword with statement ensures that the file object will properly close the file after it is used.

Example program 7 can also be written as follows:

【示例程序8】with open('关山月.txt', 'r+') as fp:    text = fp.read()    fp.seek(0)      # 将读取指针移动到文件开头    lines = text.split('。')    for line in lines:        line = line.strip() # 去除多余空行        if line:              fp.write(line + '。\n')

Summarize:

Although file manipulation is the key content of Python language teaching, it is widely used in programming practice, but from the perspective of classroom teaching and exam preparation, due to insufficient class hours and low test requirements, we do not need to deal with Python files in classroom teaching. The operation has been expanded too much, and students only need to master the opening mode of files and the basic methods of reading and writing files.

According to the principle of reviewing the old and learning the new and step-by-step, we first let students compare the differences between input, output, and read and write files on the IDLE interface, and understand the functions of input(), print(), read(), and write(); and then through specific examples, Master the basic methods ; finally, through the comprehensive training of text file reading and writing operations to help students master the knowledge they have learned .

For various reasons, when implementing the function of opening a file, the code provided by the textbook does not use the more commonly used - also highly recommended by the Python community - the with statement. As a result, the with statement does not appear in the vast majority of teaching supplementary material exercises or joint examination papers; some questions use the with statement, which has also been criticized by some teachers. What do you think about this issue?


If you need the word document, source code and after-class thinking answers of this article, you can join the "Python Algorithm Journey" knowledge planet to participate in the discussion and download files. The " Python Algorithm Journey " knowledge planet brings together a large number of friends and more interesting topics. Discuss here, and share more useful material here.

We focus on Python algorithms, if you are interested, come together!

picture

Relevant excellent articles:

Read code and write better code

The most effective way to learn

Python algorithm journey article classification

picture