习题16:读写文件
上一个练习应该记住的命令
close | 关闭文件 (跟文件编辑时的文件->保存一个意思) |
read | 读取文件内容(可以将结果赋值给一个变量) |
readline | 读取文本文件中的一行 |
truncate | 清空文件 |
write(stuff) | 将stuff写入文件 |
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')
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()
加分练习
1. 如果你觉得自己没有弄懂的话,用我们的老办法,在每一行之前加上注解,为自己理清思路。就算不能理清思路,你也可以知道自己究竟具体哪里没弄明白。
2. 写一个和上一个练习类似的脚本,使用 read 和 argv 读取你刚才新建的文件。
from sys import argv
script, filename = argv
txt = open(filename)
print(txt.read())
3. 文件中重复的地方太多了。试着用一个 target.write() 将 line1 , line2 , line3 打印出来,你可以使用字符串、格式化字符、以及转义字符。
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')
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+"\n"+line2+"\n"+line3+"\n") #用加号来连接
print("And finally, we close it.")
target.close()
4. 找出为什么我们需要给 open 多赋予一个 'w' 参数。
提示: open 对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作
因为open()默认是'r',即读取文本模式,不能进行写入; 所以需要指定写入模式, 用到参数w。
习题17:更多文件操作
from sys import argv
from os.path import exists
# 将文件名字符串作为参数,如果文件存在,返回True,否则返回False
script, from_file, to_file = argv
print("Copying from %s to %s" % (from_file, to_file))
in_put = open(from_file)
in_data = in_put.read()
print("The input file is %d bytes long" % len(in_data))
print("Does the output file exist? %r" % exists(to_file))
print("Ready, hit RTTURN to continue, CTRL-C to abort.")
input()
out_put = open(to_file, 'w')
out_put.write(in_data)
print("Alright, all done")
out_put.close()
in_put.close()
加分练习
1. 再多读读和 import 相关的材料,将 python 运行起来,试试这一条命令。试着看看自己能不能摸出点门道,当然了,即使弄不明白也没关系。
2. 这个脚本实在是有点烦人。没必要在拷贝之前问一遍把,没必要在屏幕上输出那么多东西。试着删掉脚本的一些功能,让它使用起来更加友好。
from sys import argv
script, from_file, to_file = argv
in_data = open(from_file).read()
out_put = open(to_file, 'w')
out_put.write(in_data)
out_put.close()
print(open(to_file).read())
3. 看看你能把这个脚本改多短,我可以把它写成一行。
open(to_file, 'w').write(open(from_file).read())
6. 找出为什么你需要在代码中写 output.close() 。
在第二题的代码最后有一句输出,我把它放到close之前,没有输出结果。
结合一些博客的解释,如果不写,新复制的文件不会保存内容。
out_put = open(to_file, 'w') 执行时会创建 to_file 文件,但是没内容
out_put.write(indata) 执行时,内容会写入到 to_file 的内存数据中,但仍未写入硬盘。
只有在执行 close 时 python 才指定文本的各种操作已经结束了,不会再有任何变化,这个时候在写入硬盘可以尽可能地减少硬盘读写操作,提高效率(特别在特大文件的时候)