首页 > 编程语言 > 详细

Python 文本处理

时间:2014-12-03 19:39:07      阅读:320      评论:0      收藏:0      [点我收藏+]
1 文件内容互相复制

a = open(r‘C:\Users\kk\Desktop\a.txt‘,‘r‘)
b = open(r‘C:\Users\kk\Desktop\b.txt‘,‘w+‘)

for h in a.readlines():
    b.writelines(h)
a.close()
b.close()

或者:

import shutil
shutil.copyfile(r‘C:\Users\kk\Desktop\a.txt‘, r‘C:\Users\kk\Desktop\d.txt‘) 


2 将a文件复制到b文件 并且每行长度为8个字符

a = open(r‘C:\Users\kk\Desktop\a.txt‘,‘r+‘)
b = open(r‘C:\Users\kk\Desktop\b.txt‘,‘w+‘)
i=8

for c in a.readlines():
    for h in range(0,len(c),i):
        aa = c[h:h+i]+‘\n‘
        print aa
        b.write(aa)
        
        
3  替换文本中的某行 。将文本所有行变成列表然后切片

file = open(r‘C:\Users\kk\Desktop\a.txt‘,‘r+‘)
b =  file.readlines()
b[1] = ‘hello‘

file = open(r‘C:\Users\kk\Desktop\a.txt‘,‘w+‘)
file.writelines(b)
file.close()        

4 替换文本中某个字符

import  re
file = open(r‘C:\Users\kk\Desktop\a.txt‘,‘r+‘)

open(r‘C:\Users\kk\Desktop\c.txt‘, ‘w‘).write(re.sub(‘hello‘, ‘Love python‘, file.read()))

5 查找某个字符在多少行
file = open(r‘C:\Users\kk\Desktop\a.txt‘,‘r+‘)

for h ,num in enumerate(file.readlines()):
    if num.find(‘kexl‘) >= 0:
       print h,num
file.close()


本文出自 “柯小某” 博客,请务必保留此出处http://kexl908.blog.51cto.com/605006/1585923

Python 文本处理

原文:http://kexl908.blog.51cto.com/605006/1585923

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!