python文件,,#文件操作 open


#文件操作 open()#open("路径 + 文件名",”读写模式")f=open(‘filepath‘,‘w‘) #读写模式:# r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件#常用读写模式#如:‘rb‘,‘wb‘,‘r+b‘等等#读写模式的类型有:#rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)#w      以写方式打开,#a      以追加模式打开 (从 EOF 开始, 必要时创建新文件)#r+     以读写模式打开#w+     以读写模式打开#a+     以读写模式打开#rb     以二进制读模式打开#wb     以二进制写模式打开#ab     以二进制追加模式打开#rb+    以二进制读写模式打开#wb+    以二进制读写模式打开#ab+    以二进制读写模式打开#W      若文件存在,首先要清空,然后重新创建文件#a      把所有的数据追加到文件的尾部,即使seek指在其他的位置,如果文件不存在,则重新创建 f.read([size])#size未指定则返回整个文件,如果文件大小>2倍内存则有问题.f.read()读到文件尾时返回""(空字串) file.readline()#返回一行 file.readline([size])#返回包含size行的列表,size 未指定则返回全部行 for line in f: print line#通过迭代器访问 f.write("hello\n")#如果要写入字符串以外的数据,先将他转换为字符串. f.tell()#返回一个整数,表示当前文件指针的位置(就是到文件头的比特数). f.seek(偏移量,[起始位置]) #用来移动文件指针。偏移量:单位:比特,可正可负#起始位置:0-文件头,默认值;1-当前位置;2-文件尾 f.close()#关闭文件 f = open("c:\\temp.txt","r+")   #可读可写模式f.write("123")                  #写入字符串 f = open("c:\\temp.txt","r")lines = f.readlines()           #读取全部内容for line in linesprint line

练习

#coding=utf-8def write_demo ():    f = open("123.dat",‘w‘)    f.write("hello python \n hello java\nhello python \n hello java\nhello python \n hello java\nhello python \n hello java\nhello python \n hello java\nhello python \n hello java\n")    f.close()def read_demo():    f = open("123.dat",‘r‘)    cont = f.read(11111111)    print(cont)    print("---------")    cont = f.read()    print(cont)    f.close()#write_demo()#read_demo()def readLines_demo():    f = open("123.dat",‘r‘)    cont = f.readlines()    print(type(cont))    print(cont)#readLines_demo()def read_bigFile():    f = open("123.dat",‘r‘)    cont = f.read(10)    while len(cont) >0 :        print(cont)        cont = f.read(10)#read_bigFile()def read_demo2():    f = open("123.dat",‘r+‘)    #print(f.read())    f.write("aaasdf\n1111111111111111111asdfasdfasdfasdfasdfasdfasdfadsfasdfasfd\nasdfasdfasdfasdfasdfasdf")    print(f.read())    f.close()#read_demo2()def copyFile():    f1 = "123.dat"    f2 = "123.dat.bak"    #大文件复制    fs1 = open(f1,‘r‘)    fs2 = open(f2,‘w‘)    cont1 = fs1.readline()    while len(cont1)>0:        #写入        fs2.write(cont1)        cont1 = fs1.readline()    fs1.close()    fs2.close()#copyFile()def read_random():    f=open("123.dat",‘r‘)    str1 = f.read(3)    print("read data is "+str1)    position = f.tell()    print("current position "+str(position))    str1 = f.read(3)    position = f.tell()    print("current position "+str(position))    f.close()#read_random()def read_seek():    f=open("123.dat",‘a+‘)    f.seek(5,1)#从当前位置向前偏移5个字节    f.read(3)    print("current position  "+str(f.tell()))    f.seek(10,0)#从开始的位置向前都读取10个字节    print(f.read(10))    print("current position  "+str(f.tell()))    f.seek(10,2)#从结束的位置向开始的位置读取10个字节        print(f.read(10))    print("current position  "+str(f.tell()))    f.close()read_seek()

python文件

评论关闭