Python笔记之文件
Python笔记之文件
1,文件打开和创建 #file()用于文件管理 file(name, mode [, buffering]]) name为文件名,存在-打开;不存在-创建 mode为打开模式,r, r+, w, w+, a, a+, b, U等2,读取文件
#open()读取文件 data=open(‘file_name’) #打开一个文件 print( data.redline(), end=‘ ‘) #用readline()读取一个数据行 data.seek(0) #回到文件起始位置 for line in data print(line, end=‘ ‘) data.close() #关闭文件
读取文件的方式 #1)按行读取
f = open(“file.txt”) while True: line = f.readline() if line: print line else: break; f.close()
#2)多行读取
f = open(‘file.txt’) lines=f.readlines() #readlines() 存下了f的全部内容 for line in lines print line
#3)一次性读取read()
f = open(‘file.txt’) content = f.read() print content f.close()
3,文件写入
#write(),writelines()写文件 f = file(‘file.txt’, ‘w+’) #w+读写方式打开,先删除原来的,再写入新的内容 line = [“hello \n”, “world \n”] f.writelines(li) f.close() #追加新内容 f = file(‘hello.txt’, ‘a+’) content = “goodbye” f.write( content ) f.close()
4,文件删除 #需要使用 os 模块 和 os.path 模块 #os模块的 open()和 file()函数和Python内建的用法不同
import os file(‘hello.txt’, ‘w’) if os.path.exists(‘hello.txt’) os.remove(‘hello.txt’)
5,文件复制
#用read()和write()实现拷贝 src = file(“hello.txt”, “r”) dst = file(“hello2.txt”,”w”) dst.write( src.read() ) src.close() dst.close() #shutil模块 copyfile()函数 #copyfile( src, dst) #文件复制 shutil.copyfile(“hello.txt”, “hello2.txt”) #move( src, dst) #文件剪切,移动 shutil.move(“hello.txt”, “../“) #移动到父目录下 shutil.move(“hello2.txt”, “hello3.txt”) #移动+重命名
6,文件重命名
#修改文件名 os模块的rename()函数 import os os.rename(“hello.txt”, “hi.txt”) #修改后缀名 import os files = os.listdir(“.”) for filename in files: pos = filename.find(“.”) if filename[ pos+1 :] == “html”: newname = filename[ :pos+1] + “jsp” os.rename( filename, newname)
7,文件内容查找
#文件查找 import re f1 = file(“hello.txt”, “r”) count = 0 for s in f1.readlines() : li = re.findall(“hello”, s) #findall()查询变量s,查找结果存到li中 if len( li) > 0 : count = count + li.count(“hello”) print count,”hello” f1.close() #文件替换 f1 = file(“hello.txt”, “r”) f2 = file(“hello2.txt”, “w”) for s in f1.readlines(): f2.write( s.replace(“hello”, “hi”) ) f1.close() f2.close()
8,文件比较 #difflib模块用于序列,文件的比较
9,配置文件的访问 #Python标准库的ConfigParser模块用语解析配置文件
10,文件和流
#sys模块中提供了stdin,stdout,stderr三种基本流对象 import sys #stdin表示流的标准输入 sys.stdin = open(“hello.txt”, “r”) #读取文件 for line in sys.stdin.readlines() print line #stdout重定向输出,把输出结果保存到文件中 sys.stdout = open(r”./hello.txt”, “a”) print “goodbye” sys.stdout.close()
评论关闭