使用f.seek(offset, whence)可能的異常 io.UnsupportedOperation: can’t do nonzero cur-relative seeks,沒用以binary打開的文件offset非法。
defmy_write(file_name:str):''' 只寫模式,utf-8編碼'''withopen(file_name, mode='w', encoding='utf-8')as f:f.write('hello, my name is plus Lee.\nI am come from China')defmy_read(file_name:str):''' 可讀可寫 b模式'''withopen(file=file_name, mode='rb+')as f:print(f'{file_name} b模式下的文件內容是:{f.read()}')print('當前文件位置:', f.seek(0,1),'個字符串')print(f'從第{f.seek(0, 0)}個字符開始讀,第1個字符是{f.read(1)}')print(f'設置現在位置為{f.seek(0, 0)}, 從當前位置偏移{f.seek(7, 1)}個位置后,字符為{f.readline()}')print(f'現在位置{f.tell()}, 最后一個位置{f.seek(0, 2)}, {f.readline()}')'''
這個my_read() 方法,f.seek(offset, whence) 從whence偏移offset單位長度
whence為0,從文件第一個開始讀取
whence為1,從當前位置偏移offset個長度
whence為2,從最后位置偏移offset個長度
whence 為1,或者2時易錯,要在b模式打開文件在文本文件(mode沒以 b 模式打開的文件),
只允許相對于文件開頭搜索(使用 seek(0, 2) 搜索到文件末尾是個例外)
并且唯一有效的 offset 值是從 f.tell() 中返回的或者是零。
其他 offset 值都會產生未定義的行為
'''# my_write('f:/joy/2.txt')
my_read('f:/joy/2.txt')'''
f:/joy/2.txt b模式下的文件內容是:b'hello, my name is plus Lee.\r\nI am come from China'
當前文件位置: 49 個字符串
從第0個字符開始讀,第1個字符是b'h'
設置現在位置為0, 從當前位置偏移7個位置后,字符為b'my name is plus Lee.\r\n'
現在位置29, 最后一個位置49, b''
'''