|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Python freopen
众所周知,Python 的 sys 库里面有两个东西,分别是 sys.stdin 和 sys.stdout。
看名字就知道它俩是干啥的8,一个输入,一个输出。
他俩本质是变量,所以是可以改变值的。比如,把 print 的输出定向到文件中,有两种方法:
第一种:
- print("Hello world!", file = open("我是一个文件.txt", "w", encoding = "utf-8"))
复制代码
第二种:
- import sys
- sys.stdout = open("我是一个文件.txt", "w", encoding = "utf-8")
- print("Hello world!")
复制代码
明显可以发现,后者在使用时不需要设置 file 参数,所以更加方便。
从文件里读取内容并传给 input 函数也是一个道理:
- import sys
- sys.stdin = open("我是一个文件.txt", "r", encoding = "utf-8")
- s = input()
- print(s)
复制代码
假设文件真的存在且有内容,运行一下,可以发现,打印出了文件第一行的内容。
所以不难发现,input 函数的本质其实是:
- import sys
- def input(prompt):
- print(prompt, end = "")
- return sys.stdin.readline().strip() # strip 是为了删除行尾附带的换行符
复制代码
综上所述,可以写出 freopen 函数原型:
- import sys
- # 由于使用 write 写入内容后,写入的内容会在缓冲区里而不是在文件里,所以使用 flush 刷新缓冲区
- def print(*values, end = '\n', sep = ' ', file = sys.stdout, flush = True):
- file.write(sep.join(values) + end)
- if flush: file.flush()
- def freopen(file, mode):
- # 由于 freopen 通常只用这两个文件模式,所以我就只写这俩了
- if mode == 'r':
- sys.stdin = open(file, mode, encoding = "utf-8")
- elif mode == 'w':
- sys.stdout = open(file, mode, encoding = "utf-8")
复制代码
如果你想搭建一个程序评测系统的话,这个很好用! |
|