2020/10/23:Pythonファイル操作

PYTHONファイル操作

データを処理するとき、テキストファイルを編集する必要が生じることが多く、手動編集は退屈で時間がかかります。Pythonを使用してバッチ処理を実行する方がはるかに簡単です。

コード

import re
import os

def alter(file,file1,old_str,new_str):
    file_data =""
    with open(file,"r") as f:
        for line in f:
            if old_str in line:
                line = line.replace(old_str,new_str)
            file_data +=line
    with open(file1,"w") as f:
        f.write(file_data)

alter("first.info","second.info","str1","str2")

コード分​​析

これfirst.info(file)は、元々変更が必要なファイルを
second.info指します。保存されたファイルを
str1指します。変更が必要なファイルに表示される文字列を指します。
str2置換に使用される文字列を指します。

おすすめ

転載: blog.csdn.net/weixin_43624728/article/details/109244057