笨办法学python加分习题16

本文通过一个具体的Python脚本示例,展示了如何创建、读取、更新和删除文件的基本过程。主要内容包括使用Python来创建文件、向文件中写入内容、读取文件内容等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模块名称:测试.py  python版本:3   如有错误,敬请指出
#加分习题16
#1
from sys import argv#从模块导入函数
script,filename = argv#设置参数
print("We're going to erase %r."%filename)
print("If you don't want that,hit CTRL-C(^C).")
print("If you do want that,hit RETURN.")
input("?")
print("Opening the file...")
target = open(filename,'w')#target 目标   以写入模式打开
print("Truncating the file.Goodbye")
target.truncate()#清空文档,这部分会清空你test之前写入的内容
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)
target.write("\n")#换行
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally,we close it.")
target.close()#关闭文件
#2
target = open(filename)#不要忘了重新open一下
print(target.read())
target.close()
#3
target = open(filename,'w')#没有清空文档,以'w'打开会覆盖原有文件
line1 = input("line 1 : ")
line2 = input("line 2 : ")
line3 = input("line 3 : ")
target.write("%s\n%s\n%s\n"%(line1,line2,line3))
#4略
#5略

运行结果:

PS C:\Users\user2\AppData\Local\Programs\Python\Python37\笨办法学python> python 测试.py test.txt

We're going to erase 'test.txt'.
If you don't want that,hit CTRL-C(^C).
If you do want that,hit RETURN.
?
Opening the file...
Truncating the file.Goodbye
Now I'm going to ask you for three lines.
line 1 : 1
line 2 : 2
line 3 : 3
I'm going to write these to the file.
And finally,we close it.
1
2
3


line 1 : h
line 2 : u
line 3 : i

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值