python学习-文件的读写操作
生活随笔
收集整理的這篇文章主要介紹了
python学习-文件的读写操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 文件的寫操作
- 文件的讀操作
文件的寫操作
open函數,原型:
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open參數說明:
========= ===============================================================Character Meaning--------- ---------------------------------------------------------------'r' open for reading (default)'w' open for writing, truncating the file first'x' create a new file and open it for writing'a' open for writing, appending to the end of the file if it exists'b' binary mode't' text mode (default)'+' open a disk file for updating (reading and writing)'U' universal newline mode (deprecated)========= =============================================================== ========= ===============================================================Character Meaning--------- ---------------------------------------------------------------'r' 打開以供閱讀(默認)'w' 打開進行寫入,首先截斷文件'x' 創建一個新文件并打開以進行寫入'a' 可寫的,追加到文件末尾(如果存在)'b' 二進制模式't' 文本模式(默認)'+' 打開磁盤文件以進行更新(讀取和寫入)'U' 通用換行模式(建議不使用)========= ===============================================================寫文件示例:
f = open("test1.txt", mode='w')f.write("line 1\n")f.writelines(["line 2\n", "line 3\n"])f.close()打開文件查看結果:
如果打開已存在文件,使用x模式
f = open(“test1.txt”, mode=‘x’)
文件已存在,所以不能使用x模式。
如果文件已存在,寫文件操作,使用‘a’和‘w’模式,‘a’打開文件,進行追加。‘w’打開文件,清空內容。
如果需要寫入中文,那需要設置編碼格式,因為默認是ASCII碼。
f = open("test1.txt", mode='w', encoding='utf8')f.write("第零行 \n") f.write("line 1\n")f.writelines(["line 2\n", "line 3\n"])f.close()文件的讀操作
f = open("test1.txt")print(f.read())f.close()如果文件里面存在中文,讀取會報錯,需要設置編碼格式。
代碼修改:
f = open("test1.txt", mode='r', encoding='utf8')print(f.read())f.close()當循環讀取文件完成以后,再次讀取,返回的都是空字符串,我們可以使用seek函數重新設置文件指針的位置。
f = open("test1.txt", mode='r', encoding='utf8')for lines in f:print(lines)f.seek(0) print(f.readline()) print(f.readline())f.close()
這里使用的是f.readline(),還有一個方法是f.readlines(),會一次把文件中的內容都讀出來,放到list里面,所以不推薦使用f.readlines(),如果文件太大會慢,而且可能導致內存占用太大而崩潰。
總結
以上是生活随笔為你收集整理的python学习-文件的读写操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 笔记本电脑用户名怎么更改(如何更改电脑的
- 下一篇: 200万摄像头一个月存储多少g