今天学习了python对文件读写和对文件的一些操作,例如在文件读写时使用read(),write()函数来实现对文件的读写,使用truncate()来清空文件,使用open(filename , style)来实现对打开文件的操作等。
以下记录今天遇到的两个问题:
1. 为什么在操作完文件之后,要写上close()语句关闭文件?
因为如果不写close()语句,可能刚才写入的内容还在缓冲区中没有真正写入文件,容易造成丢失。就像信封装信,装完信要把信封封上,以免信从信封中掉出。(这个例子是从论坛上看到的)
2. 为什么要使用import,import实现了什么?
import 会导入你所添加的模块,模块即函数和类的集合。就像我们在C/C++中使用的incude头文件的作用。
(附上一篇讲解import实现机制的好文:)
[链接](https://github.com/Liuchang0812/slides/blob/master/pycon2015cn/README.md)
附上两张课本实现文件读写的代码:
from sys import argv
script , filename = argv
print "We are going to earase %r" %filename
print "If you don't want that,hit CTRL-C(^C)."
print "If you do want that,hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename , 'w')
print "Truncating the file.GoodBye!"
target.truncate()
print "Now I'm going to ask you three lines."
line1 = raw_input("line1: ")
line2 = raw_input("line2: ")
line3 = raw_input("line3: ")
line4 = raw_input("line4: ")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
target.write(line4)
print "Finally , we close it."
target.close()
from sys import argv
from os.path import exists
script , from_file , to_file = argv
print "Copying from %s to %s" %(from_file , to_file)
input = open(from_file)
indata = input.read()
print "The input file is %d bytes long." %len(indata)
print "Does the output file exist? %r" %exists(to_file)
print "Ready , hit RETURN to continue,CTRL-C to abort."
raw_input()
output = open(to_file , 'w')
output.write(indata)
print "Alright, all done."
output.close()
input.close()