learnpython3thehardway视频_LearnPython3theHardWay__Excercise 16 Reading and Writing Files

建议ex15-17连起来学习

知识点: write

如果你做了上一节的study drills,你应该看到对文件,我们有各种各样的方法进行操作。下面的列表希望你记住的

close:关闭文件

read:读取文件内容

readline:只读取一行内容

truncate:清空文件。如果你的文件很重要,使用时注意

write(‘stuff’):往文件里写东西

seek(0):把光标移动到文件开始处

from sys import argv

script, filename = argv

print(f"We're going to erase {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')

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)

target.write("\n")

target.write(line2)

target.write("\n")

target.write(line3)

target.write("\n")

print("And finally, we close it.")

target.close()

What you should see

(venv) C:\Users\PycharmProjects\learnpythonthehardway>python ex16.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: 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.

Study Drills

1、如果不懂,就一行行注释,这是最有效的方法。

2、写一个跟上一节差不多的脚本,来读取刚刚创建的文件

3、试试用一行代码来取代25-30行,还是用target.write()

4、第12行,我们为什么要给 open 加参数 ‘w’ ?

5、既然用了参数 ‘w’ ,我们还需要用上 target.truncate()这个方法吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值