私はLinux上でコンパイルするにはあまりにもクリーンなC++ファイルを試しています。具体的には、バックスラッシュ '\'を#include文の中のスラッシュ「/」で置き換えようとしています(私はPythonを使用する必要があります)。 残念ながら、スクリプトは最後のブラケットを除いて、ほぼすべて削除します。私はこのスクリプトを使用していますPythonの正規表現があまりにも多くを削除します
}
:
import os
import re
for dirpath, dirnames, filenames in os.walk(".\Source", topdown=True):
for file in filenames:
file = os.path.join(dirpath, file)
tempfile = file + ".bak"
with open(tempfile, "w") as target:
with open(file) as source:
for line in source:
if "#include" in line:
re.sub("\\\\", "/", line)
target.write(line)
os.remove(file)
os.rename(tempfile, file)
編集:サイモン・フレーザーの提案を実装した後 を、スクリプトは正常に動作します。それは次のようになります。for
ループ内
for line in source:
if "#include" in line:
re.sub("\\\\", "/", line)
target.write(line)
、何もファイルtarget
に書き込まれません。
import os
import re
for dirpath, dirnames, filenames in os.walk(".\Source", topdown=True):
for file in filenames:
file = os.path.join(dirpath, file)
tempfile = file + ".bak"
with open(tempfile, "w") as target:
with open(file) as source:
for line in source:
if "#include" in line:
line = re.sub(r"\\", "/", line)
target.write(line)
os.remove(file)
os.rename(tempfile, file)
それは、このメソッドのために正規表現ライブラリを使用する必要があります:
文字列も速いかもしれ
.replace
方法を、持っていますか?それはforループを使って簡単に行うことができるので、 –質問のコードは正しく字下げされていますか? 'target.write(line)'は 'for'ループの中にないので、最後の行だけを書き出します。 –