引入模塊 os 判斷文件是否存在python
import os rs = os.path.exists('student.txt') if rs == True: print('文件存在') else: print('沒有文件!')
1 使用open()函數打開txt文件函數
1,mode 的模式 w 只能操做寫入;r 只能讀取;a向文件追加;code
w+可讀可寫;r+可讀可寫;a+可讀可追加字符串
屢次w模式下打開文本,若是文件中有數據會覆蓋原來的it
file_handle = open('1.txt',mode='w') #打開並建立 1.txt文本
2 寫入文本class
1,write寫入,沒有順序import
file_handle.write('hello,word\n') # \n 表示換行
2 writelines()函數,能將字符串寫入文件,但不會自動換行,須要手動擴展
file_handle.writelines(['hello\n','world'])
3 讀取文件數據file
1, read()函數,能讀取文件長度,但不知指定讀取全部im
2 readline() 函數默認讀取文件一行數據
3 readlines() 讀取全部行的數據,會把每個行的數據做爲一個元素,放在列表中返回
4 關閉文件,close()
student.close()
擴展 tell() 函數,seek()函數
tell()函數 返回當前文件中光標的位置 file_handle = open('1.txt') # 先讀取一行數據 content = file_handle.readline() print(content) # 獲取光標的位置 number = file_handle.tell() print(number) # seek()函數 ,調整光標位置 offset:偏移量 # 第一個參數 offset 直接指定文件的光標位置 # 第二個參數 0 直接移動到開始位置 1當前位置 2末尾位置 默認值0 file_handle.seek(0) number = file_handle.tell() print(number) content1 = file_handle.readline() print(content1)