Python行读取文件进行拷贝
2016-07-15 16:19
573 查看
每次遇到一个新语言,我首先想写的就是 行对行进行文件拷贝
刚开始没有加break,程序不会自动结束,太傻逼了,当然一行一行也很傻逼
Python提供了方法一次性读取多行
当然readlines有缓存限制,不可能全部一次性读取特别大的文件内容,具体多大没测试
Python还可以直接对文件进行循环读取
这种方式对文件进行读取确实很方便
Pyhton支持面向对象,我把上面的简单写成一个类
1、创建对象的是老是想new
2、函数参数要带一个self,否则提示参数个数不匹配,而且还必须是第一个参数
表示严重的水土不服
查了一下Python的构造函数和析构函数,所以给类加一个构造函数和析构函数
运行程序发现没有输出“构造函数”和“析构函数”
查了半天发现原来是,下划线的问题,Pyhton的构造函数和析构函数时双下划线,OK,修改一下
测试运行正常
#文件内容拷贝,行读取拷贝 f1 = open("text1.txt", "r") f2 = open("text2.txt", "a") while True: str = f1.readline() if str: f2.write(str) else: break f1.close() f2.close()
刚开始没有加break,程序不会自动结束,太傻逼了,当然一行一行也很傻逼
Python提供了方法一次性读取多行
#文件内容拷贝,行读取拷贝 f1 = open("text1.txt", "r") f2 = open("text2.txt", "a") while True: lines = f1.readlines() if lines: f2.writelines(lines) else: break f1.close() f2.close()
当然readlines有缓存限制,不可能全部一次性读取特别大的文件内容,具体多大没测试
Python还可以直接对文件进行循环读取
#文件内容拷贝,行读取拷贝 f1 = open("text1.txt", "r") f2 = open("text2.txt", "a") for line in f1: f2.write(line) f1.close() f2.close()
这种方式对文件进行读取确实很方便
Pyhton支持面向对象,我把上面的简单写成一个类
class CopyFileExcute: def copyFile(self, srcPath, destPath): f1 = open(srcPath, "r") f2 = open(destPath, "a") for line in f1: f2.write(line) f1.close() f2.close() copyFileExcute = CopyFileExcute() copyFileExcute.copyFile("text1.txt", "text2.txt")
1、创建对象的是老是想new
2、函数参数要带一个self,否则提示参数个数不匹配,而且还必须是第一个参数
表示严重的水土不服
查了一下Python的构造函数和析构函数,所以给类加一个构造函数和析构函数
class CopyFileExcute: def _init_(self): print("构造函数") def _del_(self): print("析构函数") def copyFile(self, srcPath, destPath): f1 = open(srcPath, "r") f2 = open(destPath, "a") for line in f1: f2.write(line) f1.close() f2.close() copyFileExcute = CopyFileExcute() copyFileExcute.copyFile("text1.txt", "text2.txt") del copyFileExcute
运行程序发现没有输出“构造函数”和“析构函数”
查了半天发现原来是,下划线的问题,Pyhton的构造函数和析构函数时双下划线,OK,修改一下
class CopyFileExcute: def __init__(self):#前后都是两个下划线 print("构造函数") def __del__(self):#前后都是两个下划线 print("析构函数") def copyFile(self, srcPath, destPath): f1 = open(srcPath, "r") f2 = open(destPath, "a") for line in f1: f2.write(line) f1.close() f2.close() copyFileExcute = CopyFileExcute() copyFileExcute.copyFile("text1.txt", "text2.txt") del copyFileExcute
测试运行正常
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法