笨方法学Python 习题 16: 读写文件

来源:互联网 发布:英语的网络语 编辑:程序博客网 时间:2024/04/28 01:48

#!usr/bin/python# -*-coding:utf-8-*-from sys import argvscript , filename = argvprint ("We're going to arase %r." % filename)  # 打印  We're going to arase test.txtprint ("If you don't want that, hit CTRL-C (^C).")# 打印  If you don't want that, hit CTRL-C (^C).print ("If you do want that, hit RETURN.")# 打印  If you do want that, hit RETURN.input("?")print ("Opening the file...")# 打印  Opening the file...target = open(filename,"w")#以写模式 打开test.txt#w代表写模式打开文件#r代表读模式打开文件#wr代表读写模式打开文件#w+代表读写模式打开文件#r+代表读写模式打开文件#a+代表读写模式打开文件print ("Truncating the file . Goodbye!")# 打印  Truncating the file . Goodbye!target.truncate()# 清空text.txt文件print ("Now I'm going to ask you for three lines.")# 打印  Now I'm going to ask you for three lines.line1 = input("line 1: ")line2 = input("line 2: ")line3 = input("line 3: ")# 输入line1/2/3内容print ("I'm going to write these to the file.")# 打印  I'm going to write these to the filetarget.write(line1)target.write("\n")target.write(line2)target.write("\n")target.write(line3)target.write("\n")# 写入内容  print ("And finally, we close it.")# 打印  And finally, we close it.target.close()


运行结果如下:

$ python ex16.py test.txtWe'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: To all the people out there.line 2: I say I don't like my hair.line 3: I need to shave it off.I'm going to write these to the file.And finally, we close it.$

加分习题

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

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

txt = "lx0016jft.txt" test = open(txt, "w")test.truncate()jftline1 = input(">>>>>line1:")jftline2 = input(">>>>>line2:")jftline3 = input(">>>>>line3:")jftline4 = input(">>>>>line4:")test.write(jftline1)test.write("\n")test.write(jftline2)test.write("\n")test.write(jftline3)test.write("\n")test.write(jftline4)test.write("\n")test.close()test = open("lx0016jft.txt")print (test.read())

这里在打印的时,必须得重新打开一次文档,百度查到的解释是,传送的数据还在内存中,并没有写入进文档,只有重新打开后,读取打印才能看到写入修改后的内容。

③文件中重复的地方太多了。试着用一个 target.write() 将 line1, line2, line3 打印出来,你可以使用字符串、格式化字符、以及转义字符。

test.write(jftline1 + "\n" + jftline2 + "\n" + jftline3 + "\n" + jftline4 + "\n")

④找出为什么我们需要给 open 多赋予一个 'w' 参数。提示: open 对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作。

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

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


常见问题回答

如果用了 'w' 参数, truncate() 是必须的吗?

看看加分习题 5。

'w' 是什么意思?

它只是一个特殊字符串,用来表示文件的访问模式。如果你用了 'w' 那么你的文件就是写入(write)模式。除了 'w' 以外,我们还有 'r' 表示读取(read), 'a' 表示追加(append)。

还有哪些修饰符可以用来控制文件访问?

最重要的是 + 修饰符,写法就是 'w+', 'r+', 'a+' ——这样的话文件将以同时读写的方式打开,而对于文件位置的使用也有些不同。

如果只写 open(filename) 那就使用 'r' 模式打开的吗?

是的,这是 open() 函数的默认工作方式。

原创粉丝点击