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()
时间: 2024-10-09 06:55:27