File flipping teaching python

Table of contents

Level 1 Read the entire contents of the file into a string

Level 2 Read the first n characters of the file

Level 3 Read and output file content line by line

Level 4: Read a file into a list

Level 5 Read the data in the file to a two-dimensional list

Level 6 Write Tang poems to the file


Level 1  reads the entire content of the file into a string

mission details

The task of this level: Write a small program that can read the entire content of the file into a string.

related information

In order to complete the task of this level, you need to master: 1. Opening the file 2. Reading the file to a string

file = '/data/bigfiles/出塞.txt'
with open(file, mode='r', encoding='utf-8') as f:  # 为文件对象命的名放在as后面
    txt = f.read()  # 将文件全部内容读入到字符串txt中
print(txt)

The second level  reads the first n characters of the file

mission details

The task of this level: write a small program that can read the first n characters of a file.

related information

In order to complete the task of this level, you need to master: 1. Read file to string

read file to string

2.read(size) When the parameter size is an integer greater than or equal to 0, read size characters

n = int(input())
file = '/data/bigfiles/出塞.txt'
with open(file, mode='r', encoding='utf-8') as f:  # 为文件对象命的名放在as后面
    txt = f.read(n)  # 将文件前3个字符读入到字符串txt中
print(txt)

Level 3  reads and outputs file content line by line

The task of this level: write a small program that can read and output the contents of the file line by line.

related information

In order to complete the task of this level, you need to master: 1. Read file to string 2. File pointer

read file to string

1.f.readline() reads a single line of data from a file; a newline character (\n) is reserved at the end of the string, and a blank line is represented by '\n', and the string contains only one newline character. When f.readline() returns an empty string, it means that the end of the file has been reached.

n = input()
file = '/data/bigfiles/'+n
with open(file,'r',encoding = 'utf-8') as poem:  # 打开文件创建文件对象,命名为poem
    while txt := poem.readline():  # 逐行读文件,直至文件结束
        print(txt.strip())         # 去除行末的换行符后输出当前读到的字符串

Level 4: Read a file into a list

mission details

The task of this level: write a small program that can read files into a list.

related information

In order to complete the task of this level, you need to master: 1. Read the file to the list

read file to list

1. readlines()When there is no parameter, read all the data of the file and return a list. Each element in the list is a line of data in the file object, including the newline character '\n' at the end of the line.

file = input()
with open(file, 'r', encoding='utf-8') as poem:  # 打开文件创建文件对象,命名为poem
    poem_ls = poem.readlines()  # 读取文件,到第10个字符所在的行末
print(poem_ls)

Level 5  reads the data in the file to a two-dimensional list

mission details

The task of this level: Write a small program that can read the data in the file into a two-dimensional list.

related information

In order to complete the task of this level, you need to master: 1. String segmentation 2. Traversing files to two-dimensional list

string segmentation

1. txt.split(sep)Segment the string txt according to the separator sep and return a list.

file = input()
with open('/data/bigfiles/'+file, 'r', encoding='utf-8') as fr:  # 打开文件创建文件对象,命名为poem
    score_ls = [row.strip().split(',') for row in fr]                    # 遍历文件对象,row为当前行
print(score_ls)  # 输出二维列表

Level 6  writes Tang poems into the file

According to the prompt, supplement the code in the editor on the right, input the serial number of a poem represented by a 3-digit character, read out the verse with the specified serial number from the file "/data/bigfiles/Three Hundred Tang Poems.txt", and then write the poem Separately write to the file of the behavior file name starting with the sequence number of the poem.

Test instruction

The platform will test the code you write:

Test input:237

Expected output: Created file:237刘长卿:送灵澈.txt

def get_poem(file):
    """读唐诗300首,定位到用户输入的序号的诗,将该首诗读取为一个字符串,返回去除末尾空白字符的字符串"""
    poem = ''                              # 空字符串,用于容纳目标诗
    poet_flag = False                      # 做一个标记,假定当前行不是目标诗
    with open(file, 'r', encoding='utf-8') as fr:  # 创建文件对象
            for line in fr:                    # 遍历文件对象
                # 当当前行包含序号(序号用3位数,不足3位前面补0)时,将当前行拼接到poem上,改变poet_flag的值为True
                if  line[:3] == str(num):
                    poem = poem + line
                    poet_flag = True
                elif line[0] in '0123456789':  # 若当前行不包含序号但有数字
                    poet_flag = False          # 改变标记,后续几行不是目标诗句
                elif poet_flag:                # 如果标记值为真(True)
                    poem = poem + line         # 将当前行拼接到字符串上
            return poem                        # 遍历结束后返回包含目标诗的字符串


def write_poem(line):
    """参数是包含指定序号诗句的字符串,提取诗的标题行做为要写入的文件名,将全部诗句按顺序写入到文件中,返回诗的标题行"""

    title = line.split(maxsplit=1)[0]  # 这里的maxsplit参数是最大拆分数,我们只需要拆分一次
    with open(title+'.txt', 'w', encoding='utf-8') as f:
        f.write(line)
        return title


def check_file(file):
    """参数是新创建的文件名,读取新创建并写入诗句的文件,检查是否写入成功,无返回值"""
    with open(file, 'r', encoding='utf-8') as fr:
        print(fr.read())            # 文件读取为一个字符串并输出


if __name__ == '__main__':
    filename = '/data/bigfiles/唐诗三百首.txt'  # 源文件路径
    num = input()  # 输入序号
    poem_str = get_poem(filename)     # 读取指定序号的诗为字符串
    file_title = write_poem(poem_str)  # 字符串写入文件,并返回标题
    check_file(file_title+'.txt')     # 查看写入的文件,输出诗的内容

 

Guess you like

Origin blog.csdn.net/m0_70456205/article/details/130675265