python--文件操作刪除某行


方法一:

 

import shutil
with open('/path/to/file', 'r') as f: with open('/path/to/file.new', 'w') as g: for line in f.readlines(): if '/local/server' not in line: g.write(line) shutil.move('/path/to/file.new', '/path/to/file')

 

方法二:

 

將文本中的 tasting123刪除 

1
2
3
4
5
6
7
8
with  open ( "fileread.txt" , "r" ,encoding = "utf-8" ) as f:
     lines  =  f.readlines()
     #print(lines)
with  open ( "fileread.txt" , "w" ,encoding = "utf-8" ) as f_w:
     for  line  in  lines:
         if  "tasting123"  in  line:
             continue
         f_w.write(line)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM