本文實例講述了Python3搜索及替換文件中文本的方法。分享給大家供大家參考。具體實現方法如下:
# 將文件中的某個字符串改變成另一個 # 下面代碼實現從一個特定文件或標準輸入讀取文件,# 然后替換字符串,然后寫入一個指定的文件 import os, sysnargs = len(sys.argv)if not 3 <= nargs <= 5: print('usage: %s search_text repalce_text [infile [outfile]]' % / os.path.basename(sys.argv[0]))else: search_text = sys.argv[1] replace_text = sys.argv[2] input_file = sys.stdin output_file = sys.stdout if nargs > 3: input_file = open(sys.argv[3]) if nargs > 4: output_file = open(sys.argv[4], 'w') for s in input_file: output_file.write(s.replace(search_text, replace_text)) output_file.close() input_file.close()
希望本文所述對大家的Python程序設計有所幫助。
新聞熱點
疑難解答