ファイルに書き込む
#ベター
with open('memo.txt', 'w') as f:
f.write('this is memo')
print(f)
#with使用しない場合(非推奨)
f = open('memo.txt', 'w')
f.write('this is memo.')
print(f)
f.close()
#ベター
with open('memo.txt', 'w') as f:
f.write('this is memo')
print(f)
#with使用しない場合(非推奨)
f = open('memo.txt', 'w')
f.write('this is memo.')
print(f)
f.close()
#ベター with open('memo.txt', 'w') as f: f.write('this is memo') print(f) #with使用しない場合(非推奨) f = open('memo.txt', 'w') f.write('this is memo.') print(f) f.close()
ファイルに文字を付け足す場合(append)
f = open('memo.txt', 'a')
f.write('this is memo.')
print(f)
f.close()
f = open('memo.txt', 'a')
f.write('this is memo.')
print(f)
f.close()
f = open('memo.txt', 'a') f.write('this is memo.') print(f) f.close()
ファイルの読み込み
with open('memo.txt', 'r') as f:
#通常の読み込み
print(f.read())
#一文字ずつ読み込む
while True:
line = f.readline()
print(line)
if not line:
break
#特定の塊ごとに読み込む
while True:
chunk = 2
line = f.read(chunk)
print(line)
if not line:
break
with open('memo.txt', 'r') as f:
#通常の読み込み
print(f.read())
#一文字ずつ読み込む
while True:
line = f.readline()
print(line)
if not line:
break
#特定の塊ごとに読み込む
while True:
chunk = 2
line = f.read(chunk)
print(line)
if not line:
break
with open('memo.txt', 'r') as f: #通常の読み込み print(f.read()) #一文字ずつ読み込む while True: line = f.readline() print(line) if not line: break #特定の塊ごとに読み込む while True: chunk = 2 line = f.read(chunk) print(line) if not line: break
ファイルの書き込み+読み込み
with open('memo.txt', 'w+') as f:
f.write('this is memo')
print(f)
with open('memo.txt', 'w+') as f:
f.write('this is memo')
print(f)
with open('memo.txt', 'w+') as f: f.write('this is memo') print(f)
ファイルの読み込み+書き込み
with open('memo.txt', 'r+') as f:
print(f.read())
f.write('this is memo')
print(f.read())
with open('memo.txt', 'r+') as f:
print(f.read())
f.write('this is memo')
print(f.read())
with open('memo.txt', 'r+') as f: print(f.read()) f.write('this is memo') print(f.read())
seek関数を使って移動
with open('memo.txt', 'r') as f:
print(f.tell())
print(f.read(1))
f.seek(5)
print(f.read(1))
with open('memo.txt', 'r') as f:
print(f.tell())
print(f.read(1))
f.seek(5)
print(f.read(1))
with open('memo.txt', 'r') as f: print(f.tell()) print(f.read(1)) f.seek(5) print(f.read(1))