查找复制特定字符串-文件

编写程序实现:从键盘输入整数n。从文件"in.txt"中读入n行,将其中以字母A开头的行打印到标准输出(这里指的是屏幕)中。
标准输出的每一行是字母A开头的行。若未找到符合条件的字符串,则输出"not found";若输入数据不合法(指n为小数或负数)则输出"illegal input"。

该回答引用chatgpt:

img


try:
    n = int(input("请输入整数n:"))
    if n <= 0:
        print("illegal input")
    else:
        found = False
        with open("in.txt", "r") as file:
            for line in file:
                if line.startswith("A"):
                    print(line.strip())
                    found = True

        if not found:
            print("not found")
except ValueError:
    print("illegal input")

下面是一个Python程序实现的代码:


def print_lines_starting_with_A(n):
    if not isinstance(n, int) or n <= 0:
        print("illegal input")
        return

    with open("in.txt", "r") as file:
        lines = file.readlines()

    found = False
    for line in lines:
        if line.startswith("A"):
            print(line.strip())
            found = True

    if not found:
        print("not found")


# 从键盘输入整数n
n = input("请输入整数n: ")
try:
    n = int(n)
    print_lines_starting_with_A(n)
except ValueError:
    print("illegal input")

运行程序前,需要准备好一个名为 "in.txt" 的文件,并在其中存储了要读取的文本行。

程序的思路是: