1 File Contents Copy 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 () Or: Import shutilshutil.copyfile (R ' C:\Users\kk\Desktop\a.txt ', r ' C:\Users\kk\Desktop\d.txt ') 2 Copy a file to B file and the length of each line is 8 characters a = open (R ' C:\Users\kk\Desktop\a.txt ', ' r+ ') b = open (R ' \ c \ Users\kk\desktop\b.txt ', ' w+ ') i=8for c in a.readlines (): for h In range (0,len (c), i): aa = c[h:h+i]+ ' \ n ' print aa b.write (AA) 3 Replace a line in the text . Convert all lines of text into a list and then slice 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 Replace a character in text Import refile = 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 find a character in how many lines File = open (R ' C:\Users\kk\Desktop\a.txt ', ' r+ ') for h ,num in enumerate (File.readlines ()): if num.find (' Kexl ') >= 0: print h,numfile.close ()
This article is from the "Ke Xiao" blog, please be sure to keep this source http://kexl908.blog.51cto.com/605006/1585923
Python Text Processing