笨办法学Python3 习题20 函数和文件

发布时间 2023-10-04 20:08:01作者: 萹豆

脚本函数运行内容:

  • 系统模块导入 参数变量
  • 解包参数变量(脚本变量,文件变量1)
  • 定义函数1,执行读取文件
  • 定义函数2,执行读取位置移动到文本开头
  • 定义函数3(变量1,文件变量2),执行打印变量1,读取文件变量2的一行
  • 打开文件变量1赋值刚创的文档变量3
  • 调用函数1,读取文件
  • 调用函数2,读取位置移动到文本开头
  • 1赋值给 行数变量4
  • 调用函数3(行数变量4,文档变量3) 执行读取文件第一行
  • 行数变量4加1           //       行数变量4+=1   (简写)
  • 调用函数3 (行数变量4,文档变量3)执行读取文件的是第二行
  • 行数变量4再加1
  • 调用函数3(行数变量4,文档变量3)执行读取文件的是第三行

 

 1 from sys import argv
 2 script, input_file = argv
 3 
 4 def print_all(f):                        # 定义函数1:
 5     print(f.read())                           # 该函数命令 读取测试文本    
 6 
 7 def rewind(f):                           # 定义函数2:
 8     f.seek(0)                                 # 该函数命令 读写位置移动到测试文本开头(0)代表第0个字符
 9 
10 def print_a_line(line_count, f):         # 定义函数3:
11     print(line_count, f.readline(),end="")    # 该函数命令 打印 变量行赋值,读取文本中的一行(需要提前将读取位置移动好)
12                                               # 如 readline()括号内填2,代表每次读取两个字符
13 input_txt = open(input_file)             # 打开测试文件,将文本赋值给 文本变量名
14 
15 
16 
17 print("First let's print the whole file:\n")     # 打印 首先让我们打印整个文件:
18 print_all(input_txt)                             # 调用函数1 // 读取全文本(运行后读写位置在文件最后)
19 
20 print("Now,let's rewind, kind of like a tape.\n")# 打印 现在我们倒带,有点像磁带。
21 rewind(input_txt)                                # 调用函数2 // 读写位置移动到测试文本开头(不移动的话,读写位置在最后)
22 
23 print("let's print three lines:\n")              # 打印 让我们打印三行:
24 
25 input_txt_line = 1                        # 将数字1 赋值给变量
26 print_a_line(input_txt_line, input_txt)   # 调用函数3// 打印 1,文本第一行(读取第一行后,读取位置自动到第二行)
27 
28 input_txt_line = input_txt_line + 1       # 将变量加1  赋值给原变量名
29 print_a_line(input_txt_line, input_txt)   # 调用函数3 // 打印2,文本第二行(读取第二行后,读取位置自动到第三行)
30 
31 input_txt_line = input_txt_line + 1       # 变量加1 继续赋值给原变量名
32 print_a_line(input_txt_line, input_txt)   # 调用函数3 // 打印3,文本第三行
33 
34 
35 input_txt.close()                       
PS C:\Users\Administrator\lpthw> python ex20.py test20.txt
First let's print the whole file:

This is line
This is line
This is line
Now,let's rewind, kind of like a tape.

let's print three lines:

1 This is line
2 This is line
3 This is line