1. 程式人生 > >【文件操作】讀寫文本文件

【文件操作】讀寫文本文件

一次 只讀 方式 post col 模式 all 文件 blog

【讀寫txt文件】

r:只讀

w:只寫模式【不可讀;不存在則創建;存在則清空內容】

w+:w+,寫讀【可讀,可寫】,消除文件內容,然後以讀寫方式打開文件。

#coding=utf-8

# 讀文件
def read_file():

    # 讀取文件
    read_txt = open(txt/read_txt,r)

    # 一次讀取一行
    oneline = read_txt.readline()
    print(oneline:\n,oneline)

    # 一次讀取所有行【接著上一條讀取結束往下讀】
    for line in read_txt.readlines():
        
print(lines:\n,line) # 一次讀取所有【接著上一條讀取的往下讀】 all = read_txt.read() print(all:\n,all) read_txt.close() read_file() # 寫文件 def write_file(): # w:只寫模式【不可讀;不存在則創建;存在則清空內容】 write_txt = open(txt/write_txt,w,encoding=utf-8) write_txt.write(hello\nnihao) write_txt.write(
你好) # w+,寫讀【可讀,可寫】,消除文件內容,然後以讀寫方式打開文件。 write_txt2 = open(txt/write_txt2,w+,encoding=utf-8) write_txt2.writelines(writelines:你好) write_txt2.writelines(writelines:hello) write_txt.close() write_txt2.close() write_file()

【文件操作】讀寫文本文件