zoukankan      html  css  js  c++  java
  • 《笨方法学Python》加分题16

    基础部分

     1 # 载入 sys.argv 模块,以获取脚本运行参数。
     2 from sys import argv
     3 
     4 # 将 argv 解包,并将脚本名赋值给变量 script ;将参数赋值给变量 filename。
     5 script, filename = argv
     6 
     7 # 询问是否继续编辑文件 filename
     8 print(f"We're going to erase {filename}.")
     9 print("If you don't want that, hit CTRL-C (^C).")
    10 print("If you do want that, hit RETURN.")
    11 
    12 # 等待用户输入是否继续编辑
    13 input("?")
    14 
    15 # 如果用户未输入 ctrl-c 则会继续执行
    16 print("Opening the file...")
    17 
    18 # 打开文件对象写入覆盖内容
    19 target = open(filename, 'w')
    20 
    21 # 没有指定 truncate() 的大小,所以实际上删除了文件的内容
    22 print("Truncating the file. Goodbye!")
    23 target.truncate()
    24 
    25 print("Now I'm going to ask you for three lines.")
    26 
    27 # 获取三个 input 变量的内容
    28 line1 = input("line 1: ")
    29 line2 = input("line 2: ")
    30 line3 = input("line 3: ")
    31 
    32 # 将内容写入文件(只在内存中,并未写入硬盘)
    33 print("I'm going to write these to the file.")
    34 
    35 target.write(line1)
    36 target.write("
    ")
    37 target.write(line2)
    38 target.write("
    ")
    39 target.write(line3)
    40 target.write("
    ")
    41 
    42 # 关闭文件,将文件写入硬盘
    43 print("And finally, we close it.")
    44 target.close()

     运行结果

    加分习题

    ①如果你觉得自己没有弄懂的话,用我们的老办法,在每一行之前加上注解,为自己理清思路。就算不能理清思路,你也可以知道自己究竟具体哪里没弄明白。

    ②写一个和上一个练习类似的脚本,使用 read 和 argv 读取你刚才新建的文件。

    1 from sys import argv
    2 
    3 script, filename = argv
    4 
    5 txt = open(filename)
    6 
    7 print(txt.read())

    输出结果

    16.3 优化脚本

    target.write('
    ' + line1 + '
    ' + line2 + '
    ' + line3)

    如果需要加上格式化字符,可以这样写

    1 旧%格式串:
    2 target.write('%s
    %s
    %s
    ' %(line1,line2,line3))
    3 
    4 新format()格式串:
    5 target.write('{}
    {}
    {}
    '.format(line1,line2,line3))

     

    16.4 open 为什么多了一个 w 参数

    open() 的默认参数是 open(file, 'r') 也就是读取文本的模式,默认参数可以不用填写。而本题练习是写入文件,因此不适应使用 r 参数,需要指定写入模式,因此需要增加 w 参数。

    16.4 如果你用 'w' 模式打开文件,那么你是不是还要 target.truncate() 呢?阅读以下 Python 的 open 函数的文档找找答案。

    target.truncate() 是清空的意思,与“w”模式并不冲突,也并非后置条件

  • 相关阅读:
    教程:在 Visual Studio 中开始使用 Flask Web 框架
    教程:Visual Studio 中的 Django Web 框架入门
    vs2017下发现解决python运行出现‘No module named "XXX""的解决办法
    《sqlite权威指南》读书笔记 (一)
    SQL Server手工插入标识列
    hdu 3729 I'm Telling the Truth 二分图匹配
    HDU 3065 AC自动机 裸题
    hdu 3720 Arranging Your Team 枚举
    virtualbox 虚拟3台虚拟机搭建hadoop集群
    sqlserver 数据行统计,秒查语句
  • 原文地址:https://www.cnblogs.com/python2webdata/p/10044716.html
Copyright © 2011-2022 走看看