Tcler 的 Python 学习概要:文件读写
Tcl 里面的 File IO
set fp [open $file "r"]
set line [gets $fp]
set text [read $fp 16]
set text [read $fp]
close $fp
- 文本读写:
open $file "r"
- 二进制读写:
open $file "rb"
Python 里面的 File IO
用open()
函数打开文件。
fp = open(file_path, "rb") # 打开文件
line = fp.readline() # 读取一行
blob = fp.read(16) # 读取16字节
blob = fp.read(-1) # 读取直到文件结束
fp.close()
一种便捷的写法,可以省去close()
的调用。
with open(file_path, "rb") as file:
blob = file.read(-1)
文件读写示例
def read_text(file_path):
with open(file_path, "r") as file:
text = file.read(-1)
read text
def read_blob(file_path):
with open(file_path, "rb") as file:
blob = file.read(-1)
read blob
Python IO Class
io.IOBase
RawIOBase
extendIOBase
FileIO(name, mode, ...)
BufferedIOBase
extendIOBase
BytesIO(b"abcdef")
BufferedReader(raw, ...
BufferedWriter(raw, ...)
BufferedRandom(raw)
BufferedRWPair(reader, writer, ...)
类似于一个 pipe
TextIOBase
extendIOBase
TextIOWrapper(buffer, ...)
StringIO("abcdef", "\n")
IncrementalNewlineDecoder