hakeの日記

Windows環境でプログラミングの勉強をしています。

python - テキストファイルアクセス

# 一括リード
f = open("test.txt","r")
data = f.read()
print(data)
f.close()


with open(filename, opt) as f とすると、close()を明示しなくても良いので楽。
rubyのFile.open(filename, opt){|f| do_something }と同じ?

#coding: cp932

# 一括リード
with open("test.txt","r") as f:
	data = f.read()
	print(data)


# 一行ずつリード
with open("test.txt","r") as f:
	line = f.readline()
	while line:
		print(line, end="")
		line = f.readline()


# 一行ずつリード
with open("test.txt","r") as f:
	for line in f:
		print(line.rstrip("\n")) # 行末の改行コードを削除している。


# ライト
with open("test.txt","w") as f:
	f.write("一行目\n")
	f.write("二行目\n")
	f.write("三行目\n")