Python - Python 操作文件

Python - Python 操作文件


1、代碼及其說明

if __name__ == '__main__':
    # 寫入文件
    file = open('C://Users//A-PC//Desktop//1.txt', 'w')
    file.write('Good')
    file.write('Good - ')
    file.write('\nGood - ')
    file.close()

    # 讀取文件
    file = open('C://Users//A-PC//Desktop//1.txt')
    value = file.read()
    print(value)
    file.close()

    # 讀取一行
    file = open('C://Users//A-PC//Desktop//1.txt')
    line = file.readline()
    print(line)
    file.close()

    # 讀取所有行
    file = open('C://Users//A-PC//Desktop//1.txt')
    line = file.readlines()
    print(line)
    file.close()

    # 按行讀取文件
    file = open('C://Users//A-PC//Desktop//1.txt')
    for l in file:
        print(l, end='')
    file.close()

輸出

GoodGood - 
Good - 
GoodGood - 

['GoodGood - \n', 'Good - ']
GoodGood - 
Good - 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章