1. 程式人生 > 其它 >Python讀寫檔案

Python讀寫檔案

技術標籤:Pythonpython

if __name__ == '__main__':

    # 一次性讀取檔案所有內容
    with open('temp.txt', 'r') as file:
        data = file.read()
        print(data)
    print('----------------------')
    file.close()

    # 按行讀取檔案
    with open('temp.txt', 'r') as file:
        line_index = 1
        while True
: data = file.readline() print('line %d: %s' % (line_index, data)) line_index += 1 if not data: break print('----------------------') file.close() # 一次性讀入所有行 with open('temp.txt', 'r') as file: data_list = file.
readlines() print(data_list) # 刪除所有空行:從後向前遍歷,防止越界 for index in range(len(data_list) - 1, -1, -1): data_list[index] = data_list[index].strip() if ''.__eq__(data_list[index]): data_list.pop(index) print(data_list) print('----------------------'
) file.close() # 向檔案中追加寫入 with open('temp.txt', 'a+') as file: file.write('Hello world!') print('----------------------') file.close() pass