【问题标题】:Taking Input from an external file in Python从 Python 中的外部文件获取输入
【发布时间】:2018-03-30 11:55:50
【问题描述】:
如果您遇到过针对大量输入测试您的程序的情况,您会想知道是否有捷径可走。
当您在处理大量输入时必须测试程序时间和空间复杂度时,某些方法通常会非常方便
你不能总是手动输入一些大的输入,所以有一种方法可以使用外部 txt 文件为程序提供输入
下面是我的回答:)
【问题讨论】:
标签:
python
file
input
output
external
【解决方案1】:
您只需编写简单的程序,然后在 Windows/Linux 等任何平台上从命令行运行它。
python program.py < input.txt > output.txt
是重定向运算符,它只是将标准输入和标准输出重定向到 input.txt 和 output.txt。这是最简单的方法。
或者,您可以执行以下操作
import sys sys.stdin=open('input.txt','r') sys.stdout=open('output.txt','w')
或者,您可以执行以下操作
input=open('input.txt','r')
ouput=open('ouput.txt','w')
n=input.read()
output.write(n)
我更喜欢方法 1,因为它简单且不需要文件处理,这对 Codejam、FaceBook HackerCup 有很大帮助。希望对你有帮助