# 输入输出
# 命令行输入输出
- python输入的类型永远是字符串型(str),其他的需要类型转换
# 文件输入输出
命令行的输入输出,只是 Python 交互的最基本方式,适用一些简单小程序的交互。而生产级别的 Python 代码,大部分 I/O 则来自于文件、网络、其他进程的消息等等。
我们用 open() 函数拿到文件的指针。
其中,第一个参数指定文件位置(相对位置或者绝对位置);
第二个参数,如果是 'r'表示读取,如果是'w' 则表示写入,当然也可以用 'rw' ,表示读写都要。a 则是一个不太常用(但也很有用)的参数,表示追加(append),这样打开的文件,如果需要写入,会从原始文件的最末尾开始写入。
完整语法格式
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
文件输入输出需要对内存占用和磁盘占用要有充分的估计,防止程序出错
# readline自动补全
import readline
import loguru
def complete(text, state):
loguru.logger.debug(f"complete(text={text}, state={state})")
try:
if text == 'h':
return ['hello', 'hi', 'howdy'][state]
elif text == 'w':
return ['world'][state]
except IndexError:
return None
readline.set_completer(complete)
readline.parse_and_bind("tab: complete")
while True:
a = input()
print(a)