[教學] Python 讀取 寫入 檔案(file)

顯示檔案全部內容:

file = open('考卷.txt','r')
txt=file.read()
print(txt)
file.close()
r 代表讀取
寫入
a 寫入在文件最後面
b 二進位模式

讀取一行:

txt=file.readline()
print(txt)

也可以用while迴圈的方式讀取全部檔案:
file = open('考卷.txt','r')
while True:
    txt = file.readline()
    if not txt: break
    print(txt, end='')
file.close()

注意大小寫和段落

清空檔案並寫入:
file = open('考卷.txt','w')
file.write('ruyut.com')
file.close()

在檔案最後面寫入:
file = open('考卷.txt','a')
file.write('ruyut.com')
file.close()


留言