Python 文本處理

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()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章