《笨方法学python》第四天
来源:互联网 发布:慈溪行知职高好吗 编辑:程序博客网 时间:2024/06/04 22:02
今天学习了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 argvscript , filename = argvprint "We are going to earase %r" %filenameprint "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 argvfrom os.path import existsscript , from_file , to_file = argvprint "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
- 《笨方法学python》第四天
- 笨方法学python第四版.pdf 下载地址
- 笨方法学python(本文为阅读时从此书摘录的笔记) 第四天
- 笨方法学python(本文为阅读时从此书摘录的笔记) 第四天
- 《笨方法学python》第二天
- 《笨方法学python》-2
- 《笨方法学python》-3
- 《笨方法学python》-4
- 笨方法学python 15
- 笨办法学 Python · 续 第四部分:进阶项目
- python, del[] 用法, 笨方法学python
- 笨方法学Python 习题 3: 数字和数学计算
- 《笨方法学Python》学习笔记
- 笨方法学python 有用的Tips
- 《笨方法学python-6》之lambda
- 笨方法学Python(1-5)
- 笨方法学Python(6-10)
- 笨方法学Python(11-15)
- ####好#####DStreams上的输出操作
- h5中的画布----Canvas
- Examples with HiveSemanticAnalyzerHook org.apache.hadoop.hive.ql.parse.HiveSemanticAnalyzerHook used
- Mysql(Laravel)实现按天分组查询数据
- ajax请求成功后location.href没有跳转
- 《笨方法学python》第四天
- BuildAnimationController
- Android报错:Parent file doesn't exist:/Users/XXX/Library/Caches/AndroidStudio2.3/caches/
- MongoDB与python的交互
- 基于深度学习的目标检测技术演进(转)
- C++中的new和delete
- 【Scikit-Learn 中文文档】四十六:模型选择:选择估计量及其参数
- 学习js基础知识的疑惑及解答
- JAVA后端,拼接URL访问,特殊字符异常处理