您的位置:首页 > 编程语言 > Python开发

Python行读取文件进行拷贝

2016-07-15 16:19 573 查看
每次遇到一个新语言,我首先想写的就是 行对行进行文件拷贝

#文件内容拷贝,行读取拷贝

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 IO-类