python中的文件内容操作

python中的文件内容操作
一、读文件内容
#第二个参数默认为r:读文本文件
file_object = open('thefile.txt')
try:
     all_the_text = file_object.read( )
finally:
     file_object.close( )

注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。

#读每行
list_of_all_the_lines = file_object.readlines( )

#每次调用 readlines(sizehint) 函数,会返回大约 2MB 的数据
file = open('test.log', 'r')
sizehint = 2097152   # 2M
position = 0
lines = file.readlines(sizehint)
while not file.tell() - position < 0:       
    position = file.tell()       
    lines = file.readlines(sizehint)



如果文件是文本文件,还可以直接遍历文件对象获取每行:
for line in file_object:
     process line


#读二进制文件
input = open('data', 'rb')

#读固定字节
file_object = open('abinfile', 'rb')
try:
    while True:
         chunk = file_object.read(100)
        if not chunk:
            break
         do_something_with(chunk)
finally:
     file_object.close( )



二、写文件
写文本文件
output = open('data', 'w')

写二进制文件
output = open('data', 'wb')

追加写文件
output = open('data', 'w+')


写数据
file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )


写入多行
file_object.writelines(list_of_text_strings)

注意,调用writelines写入多行在性能上会比使用write一次性写入要高。


#在第二行插入一行字符串
fp = file('data.txt')
lines = []
for line in fp: # 内置的迭代器, 效率很高
    lines.append(line)
fp.close()

lines.insert(1, 'a new line') # 在第二行插入
s = '\n'.join(lines)
fp = file('data.txt', 'w')
fp.write(s)
fp.close()


四、file对象的属性和方法

1.属性:
closed #标记文件是否已经关闭,由close()改写 
encoding #文件编码 
mode #打开模式 
name #文件名 
newlines #文件中用到的换行模式,是一个tuple 
softspace #boolean型,一般为0,据说用于print


2.file的读写方法:
F.read([size]) #size为读取的长度,以byte为单位 

F.readline([size]) 
#读一行,如果定义了size,有可能返回的只是一行的一部分 

F.readlines([size]) 
#把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。 

F.write(str) 
#把str写到文件中,write()并不会在str后加上一个换行符 

F.writelines(seq) 
#把seq的内容全部写到文件中。这个函数也只是忠实地写入,不会在每行后面加上任何东西。


3.file的其他方法:
F.close() 
#关闭文件。python会在一个文件不用后自动关闭文件,不过这一功能没有保证,最好还是养成自己关闭的习惯。如果一个文件在关闭后还对其进行操作会产生ValueError 

F.flush() 
#把缓冲区的内容写入硬盘 

F.fileno() 
#返回一个长整型的”文件标签“ 

F.isatty() 
#文件是否是一个终端设备文件(unix系统中的) 

F.tell() 
#返回文件操作标记的当前位置,以文件的开头为原点 

F.next() 
#返回下一行,并将文件操作标记位移到下一行。把一个file用于for ... in file这样的语句时,就是调用next()函数来实现遍历的。 

F.seek(offset[,whence]) 
#将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,
whence为0时表示从文件头部开始向后移动“偏移量”字节。
whence为1时表示以当前位置为原点向后移动“偏移量”字节。
whence为2时表示以文件末尾为原点向前移动“偏移量”字节。
需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。 

F.truncate([size]) 
#把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。无参数size时表示清空文件内容。



五、读写文件的基本Demo

#! /usr/bin/python
import os,sys

#打印文件属性
try:
    fsock = open("D:/SVNtest/test.py", "r")
except IOError:
    print "The file don't exist, Please double check!"
    exit()
print 'The file mode is ',fsock.mode
print 'The file name is ',fsock.name
P = fsock.tell()
print 'the postion is %d' %(P)
fsock.close()

#打印文件内容
fsock = open("D:/SVNtest/test.py", "r")
AllLines = fsock.readlines()
#Method 1
for EachLine in fsock:
    print EachLine

#Method 2
print 'Star'+'='*30
for EachLine in AllLines:
    print EachLine
print 'End'+'='*30
fsock.close()

#写文件
fsock = open("D:/SVNtest/test.py", "a")
fsock.write("""
#Line 1 Just for test purpose
#Line 2 Just for test purpose
#Line 3 Just for test purpose""")
fsock.close()


#检查文件是否处于关闭状态
S1 = fsock.closed
if True == S1:
    print 'the file is closed'
else:
    print 'The file donot close'

六、文件分割(按大小)
 import sys,os

 kilobytes = 1024
 megabytes = kilobytes*1024
 chunksize = int(200*megabytes)#default chunksize

 def split(fromfile,todir,chunksize=chunksize):
     if not os.path.exists(todir):#check whether todir exists or not
         os.mkdir(todir)          
     else:
         for fname in os.listdir(todir):
             os.remove(os.path.join(todir,fname))
     partnum = 0
     inputfile = open(fromfile,'rb')#open the fromfile
     while True:
         chunk = inputfile.read(chunksize)
         if not chunk:             #check the chunk is empty
             break
         partnum += 1
         filename = os.path.join(todir,('part%04d'%partnum))
         fileobj = open(filename,'wb')#make partfile
         fileobj.write(chunk)         #write data into partfile
         fileobj.close()
     return partnum

 if __name__=='__main__':
         fromfile  = input('File to be split?')
         todir     = input('Directory to store part files?')
         chunksize = int(input('Chunksize to be split?'))
         absfrom,absto = map(os.path.abspath,[fromfile,todir])
         print('Splitting',absfrom,'to',absto,'by',chunksize)
         try:
             parts = split(fromfile,todir,chunksize)
         except:
             print('Error during split:')
             print(sys.exc_info()[0],sys.exc_info()[1])
         else:
             print('分割完成:',parts,'parts are in',absto)


七、合并文件

 import sys,os

 def joinfile(fromdir,filename,todir):
     if not os.path.exists(todir):
         os.mkdir(todir)
     if not os.path.exists(fromdir):
         print('Wrong directory')
     outfile = open(os.path.join(todir,filename),'wb')
     files = os.listdir(fromdir) #list all the part files in the directory
     files.sort()                #sort part files to read in order
     for file in files:
         filepath = os.path.join(fromdir,file)
         infile = open(filepath,'rb')
         data = infile.read()
         outfile.write(data)
         infile.close()
     outfile.close()

 if __name__=='__main__':
         fromdir = input('Directory containing part files?')
         filename = input('Name of file to be recreated?')
         todir   = input('Directory to store recreated file?')

         try:
             joinfile(fromdir,filename,todir)
         except:
             print('Error joining files:')
             print(sys.exc_info()[0],sys.exc_info()[1])



问题1:你知道怎么快速的在文本文件中间指定行插入一行吗?
这个问题在后面详细讨论。

问题2:文件的删除、复制、剪切、遍历该怎么操作?
这需要用到os模块,详细的在另外的文章中总结。
#删除文件
import os
os.remove(file)
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值