ファイルを上書きするにはどうすればよいですか?
読み書きしたいファイルを用意します。
Python Guide and Java Guide
方法1.write()を使ってファイルを上書きする
file = open(r'C:\Users\p\Documents\program\filename.txt', "w")
file.write("Python Guide")
file.write("\nThis text will overwrite the previous one.")
file.close()
Python Guide and Java Guide
This text will overwrite the previous one.
方法2.trancate()を使ってファイルを上書きする
file = open(r'C:\Users\p\Documents\program\filename.txt', "r+")
file.truncate(0)
file.write("This text will overwrite the previous one.")
file.close()
This text will overwrite the previous one.
方法3.fileのwモードを使ってファイルを上書きする
with open(r'C:\Users\p\Documents\program\filename.txt', "w") as file:
file.write("This text will overwrite the previous one.")
This text will overwrite the previous one.
方法4.shutilモジュールを使ってファイルを上書きする
import shutil
shutil.copyfile("newfile.txt", "filename.txt")
newfile.txtの内容をfilename.txtにコピーし、内容がすでに存在する場合は上書きします。
方法5.osモジュールを使ってファイルを上書きする
import os
os.remove(r'C:\Users\p\Documents\program\filename.txt')
with open("filename.txt", "w") as file:
file.write("This text will overwrite the previous one.")
This text will overwrite the previous one.
方法6.pathlibモジュールを使ってファイルを上書きする
from pathlib import Path
file = Path(r'C:\Users\p\Documents\program\filename.txt')
file.write_text("Overwrite the Text File")
Overwrite the Text File
Python には、write()メソッド、truncate()メソッド、モードw、shutilモジュール、osモジュール、pathlibモジュールなど、ファイルを上書きするためのメソッドがいくつかあります。