“笨办法”学Python 3 ——练习 16 读写文件

练习16源代码

from sys import argv

script,filename = argv #定义2个参数

print(f"We're going to erase {filename}")  #函数filename格式化为字符串
print("If you don't want that,hit CTRL-C(^C).") #打印字符串
print("IF you do want that,hit RETURN.")#打印字符串

input("?") #input函数,根据上面提示操作

print("Opening the file...")
target = open(filename,'w') #打开文件,写入

print("Truncating the file.Goodbye!")
target.truncate()  #清空目标文件

print("Now I'm going to ask you for three lines.") 

#输入数据
line1 = input("line 1: ") 
line2 = input("line 2: ")
line3 = input("line 3: ")

print("I'm going to write these to the file.")

target.write(line1) #写入line1内容
target.write("\n") #转义字符,换行
target.write(line2) #写入line2
target.write("\n") 
target.write(line3) #写入line3
target.write("\n")

print("And finally,we close it.")
target.close() #关闭文件,类似保存

输出结果

We're going to erase C:\Users\limin\Desktop\Python3_exercises\text_16.txt
If you don't want that,hit CTRL-C(^C).
IF you do want that,hit RETURN.
?   #点击Enter键
Opening the file...
Truncating the file.Goodbye!
Now I'm going to ask you for three lines.
line 1: Mary had a little lamb
line 2: Its fleece was white as snow
line 3: It was also tasty
I'm going to write these to the file.
And finally,we close it.

知识点:

  1. 文件写入write()函数。
  2. truncate()函数,清空文件。
  3. 使用open函数打开文件时,若文件不存在会创建一个
  4. open函数的模式:
    ① r 只读方式打开。默认模式,文件指针指向文件开头,文件不存在会抛出异常。
    ② w 只写方式打开。如果文件存在则会被覆盖,不存在则会创建新文件。
    ③ a 追加方式打开。文件存在则文件指针会移动到文件末尾,不存在则创建新文件进行写入。
    ④ r+ 读写方式打开。文件指针指向文件开头,若文件不存在则抛出异常。
    ⑤ w+ 读写方式打开。文件存在会被覆盖,不存在则创建新文件。
    ⑥ a+ 读写方式打开。文件存在则文件指针放在文件结尾,不存在则创建新文件进行写入。

附加练习

  1. 写一个类似于上个练习的脚本,使用 read 和 argv 来读取你刚刚创建的文件。
    在原脚本文件中加入以下内容。
txt = open(filename,'r') #只读模式打开
print(f"This is {filename}.")
print(txt.read()) #打印读取的文件内容

print("Now,we close it again.")
txt.close()
  1. 这个练习中有太多的重复,试着用一个 target.write() 命令来打印 line1、line2、line3,你可以使用字符串、格式字符串和转义字符。
line = [line1,"\n",line2,"\n",line3]
target.writelines(line)   #writelines 可以传入字符串也可以传入一个字符序列(不能是数字序列)

3.弄明白为什么我们要用一个 ‘w’ 作为一个额外的参数来打开。
通过明确说明你想要写入一个文件,来安全地打开它。

4.如果你用 w 模式打开文件,那你还需要 target.truncate() 吗?
不需要,因为w只写方式打开,如果文件存在则会被覆盖,不存在则会创建新文件。

常见问题

  1. write和writelines的区别

① write()需要传入一个字符串做为参数,否则会报错

target.write(line1) #写入line1内容

② writelines()可以传入字符串也可以传入一个字符序列(不能是数字序列)

line = [line1,"\n",line2,"\n",line3]
target.writelines(line)  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值