python笔记:文件读写 ##读文件 ```python file_object = open("d:/test.txt", "r") for line in file_object: print line file_object.close() #or with open(filePath, 'r') as f: return f.read() # or py3 with open(filename, mode='r', encoding='ISO-8859-15') as f: return f.read() # or codecs with codecs.open(filename, "r", 'utf-8') as f: f.read() ``` ##写文件 ```python file_object = open("d:/test.txt", "w") file_object.write("hello\r\n") file_object.write("world") file_object.close() # or with codecs.open(filename, "w+", 'utf-8') as f: f.write(res) ``` ##同时操作两个 with函数是可以同时操作N个文件流的,比如下面这个例子,对文件加密: ``` with open("./test_hello.txt", mode='rb') as r, open("./test_encrypt.data", mode='wb+') as w: while 1: data = r.read(buffer) if not data: break w.write(encrypt.encrypt(data, "yzh")) ``` ##改名删除 ```python try: os.rename("d:/test.txt","d:/test123.txt") print "rename" except: print "pass" os.remove("d:/test123.txt") shutil.copy("source", \ "destination") ``` ##判定文件是否存在,是否为目录 ```python print os.path.isdir("d:/test.txt") print os.path.isfile("d:/test.txt") ``` ##遍历文件夹 ```python import os filesNum = 0 for root,dirs,files in os.walk("d:\个人笔记"): filesNum+=len(files) print("根目录:",root,"文件夹:",dirs,"文件:",files,"\n") print("文件总数",filesNum) ``` 来自 大脸猫 写于 2016-05-17 15:01 -- 更新于2020-10-19 13:06 -- 0 条评论