Python 文件操作实现代码

open(filename,mode,buffer)其中第一个参数是要打开的文件的文件名,必选;第二个是打开方式,可选;第三个为缓冲区,可选。默认情况下是以“读”模式打开文件。该函数返回的是流类型对象。mode有如下几种:r:读模式(默认值) w:写模式a:追加写模式b:二进制模式t:文本模式(默认值)+:更新已有硬盘文件(读和写模式)U:通用换行模式(Universal new line mode)如果到打开的文件不存在或者其他问题,会跑出IOError异常。常用的文件对象属性:mode:文件打开模式name:打开的文件名称closed:文件是否关闭常用的文件对象方法有:tell():获取在当前文件中,目前所处的位置。起始值为0.seek(position,mode):在当前文件中移动。其中第一个参数是要移动的距离,第二个参数是模式:0表示移动绝对位置,相对于文件头而言;1表示移动相对位置,就当前位置而言;2表示相对于文件尾的位置。read(max_byte_num):从文件中读取字节。max_byte_number为可选参数,表示读取的最大字节数。如果不选,默认为读取到文件尾。读取后,当前位置会发生变化,即增加读取的字节数。readline():一次读取文件的一行。write(content):向文件中写数据。content为要写入的内容。close():关闭文件一个文件读写的例子:

复制代码 代码如下:

try:f = open(‘d:/hello_python.txt’,’w’)f.write(‘hello my friend python!’)except IOError:print(‘IOError’)finally:f.close()try:f = open(‘d:/hello_python.txt’,’r’)print(f.read())f.close()f.tell()except ValueError as ioerror:print(‘File alread closed {0}’.format(type(ioerror)))finally:print(‘operation end’)

首先是建立关联…假设在存在以下文件 e:test.txt

This is line #1This is line #2This is line #3END>>> f = file(‘e:\test.txt’, ‘r’)

关键字的第一部分,是文件路径及名称。注意这里面,路径需要用\

第二部分,是对文件的模式或者叫权限,一般有以下3种 “r” (read), “w” (write)和 “a”(append).

之后,就可以利用

f_content = infile.read()f_content = infile.readlines()

来读取文件内容了

>>> f = file(‘e:\test.txt’, ‘r’)>>> ff_content = f.read()>>> print f_contentThis is line #1This is line #2This is line #3END>>> f.close()>>>>>> infile = file(‘e:\test.txt’, ‘r’)>>> f = file(‘e:\test.txt’, ‘r’)>>> for f_line in f.readlines():print ‘Line:’, f_lineLine: This is line #1Line: This is line #2Line: This is line #3Line: END>>> f.close()>>>

然后是文件的写入

>>> f=file(‘e:\test.txt’,’w’)>>> f.write(‘billrice’)>>> f.write(‘testtest’)>>> f.write(‘entern’)>>> f.writelines([‘billrice’,’ricerice’])>>> f.close()>>>>>> f=file(‘e:\test.txt’,’r’)>>> content=f.read()>>> print contentbillricetesttestenterbillricericerice>>>

在Python文件操作中,需要注意的是…在f.close()之前,c盘下面只有一个空空的test.txt,f.close()的作用相当于最后的存盘。

删除文件:

name=’e:1.txt’os.remove(name)

压缩文件:

import osimport zipfileimport time# 压缩目录source_dir= r’F:web’# 按时间生成文件名称target_file = time.strftime(‘%Y%m%d%H%M%S’) + ‘.zip’myZipFile = zipfile.ZipFile(target_file, ‘w’ )# 压缩所有文件,包含子目录for root,dirs,files in os.walk(source_dir):for vfileName in files:fileName = os.path.join(root,vfileName)myZipFile.write( fileName, fileName, zipfile.ZIP_DEFLATED )# 压缩完成myZipFile.close()

Python 文件操作实现代码

相关文章:

你感兴趣的文章:

标签云: