split
の変数に各テキスト部分を割り当てて、別の順序で書き出すことができます。私もファイルを開くには、コンテキストマネージャを使用して、ファイルオブジェクトに直接ではなく、readline
何も返さないまで無限ループを反復処理しています
with open("textfile.txt") as f1, open("textfile2.txt", "w") as f2:
for line in f1:
text1, numbers, text2 = line.split(":")
# N.B. this will fail if there are more *or* less than 3 parts to line.split(":")
# on any line of the file. Ensure that there is not, or wrap this in a
# try/except block and handle appropriately.
f2.write("{}:{}:{}\n".format(text1, text2, numbers))
# or f2.write(':'.join([text1, text2, numbers, "\n"]))
# or f2.write(text1 + ":" + text2 + ":" + numbers + "\n")
# or any other way to assemble the text you want.
# my favorite in Py3.6+ is an f-string
# f2.write(f"{text1}:{text2}:{numbers}\n")
注意。明示的なopen
とclose
ステートメントよりコンテキストマネージャーを優先するべきです。なぜなら、出口がクリーンでない(例外がスローされ、処理されたなどであっても)ブロックから出てもファイルオブジェクトを確実に閉じるからです。無限ループで一度に行を読み込むのではなく、ファイルオブジェクトを反復することは、イディオム的に見栄えの良いことです。
どのように実際。何を試しましたか? –
あなたはこれまでに何を試しましたか?あなたのコードを投稿してください。 – James
"text1"と "text2"の例は何ですか? – realharry