《笨方法学python》第四天

今天学习了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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值