比方说,我想要写一个从.txt文件中获取一些基本输入的函数,比如一些数字,我想在另一个.txt文件中打印这些数字乘以2。
有人教我可以导入sys并将sys.stdin和sys.stdout重定向到这些文件,就是这样
import sys
def multiply(filein, fileout):
global stdin
global stdout
origin=sys.stdin #saving the original stdin and stdout
origout=sys.stdout
sys.stdin=open(filein,'r')
sys.stdout=open(fileout,'w')
for line in sys.stdin:
nlist = [float(num) for num in line.split()] #the line is now split and each number is converted to float
for num in nlist:
sys.stdout.write((f'{num*2} ')) #each number gets multiplied by 2 and converted back to string
sys.stdout.write('\n') #just to keep each line divided
sys.stdin.close()
sys.stdout.close()
sys.stdin=origin
sys.stdout=origout一切都很好,但后来我意识到我正在导入一个库,将标准输入和标准输出重定向到正确的文件,只是为了立即将它们重定向到它们最初的位置。
这就是with语句出现在我脑海中的时候。这是完全相同的函数,但我使用的是with,而不是整个stdin和stdout重定向的想法。
def multiply(filein, fileout):
with open(filein,'r') as fin, open(fileout,'w') as fout:
for line in fin:
nlist = [float(num) for num in line.split()]
for num in nlist:
fout.write((f'{num*2} '))
fout.write('\n')在我看来这就没那么笨拙了。
我想知道为什么我更喜欢第一个版本而不是第二个版本的主要原因(如果有的话)。谢谢。
发布于 2021-01-27 01:59:06
我想知道为什么我更喜欢第一个版本而不是第二个版本的主要原因(如果有的话)。
我什么也想不到。
with上下文管理器就是为了去掉第一个示例中的所有样板代码。此外,如果出现错误,它会释放资源,这是第一个示例所没有的。
https://stackoverflow.com/questions/65906553
复制相似问题