Python行读取文件进行拷贝

来源:互联网 发布:免费手机数据恢复 编辑:程序博客网 时间:2024/05/18 01:27

每次遇到一个新语言,我首先想写的就是 行对行进行文件拷贝

#文件内容拷贝,行读取拷贝f1 = open("text1.txt", "r")f2 = open("text2.txt", "a")while True:    str = f1.readline()    if str:        f2.write(str)    else:        breakf1.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:        breakf1.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

测试运行正常

0 0