首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >临时打开一个文件以使用其内容作为输入: with-statement还是redirect sys.stdin?

临时打开一个文件以使用其内容作为输入: with-statement还是redirect sys.stdin?
EN

Stack Overflow用户
提问于 2021-01-27 01:51:23
回答 1查看 22关注 0票数 0

比方说,我想要写一个从.txt文件中获取一些基本输入的函数,比如一些数字,我想在另一个.txt文件中打印这些数字乘以2。

有人教我可以导入sys并将sys.stdinsys.stdout重定向到这些文件,就是这样

代码语言:javascript
复制
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,而不是整个stdinstdout重定向的想法。

代码语言:javascript
复制
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')

在我看来这就没那么笨拙了。

我想知道为什么我更喜欢第一个版本而不是第二个版本的主要原因(如果有的话)。谢谢。

EN

回答 1

Stack Overflow用户

发布于 2021-01-27 01:59:06

我想知道为什么我更喜欢第一个版本而不是第二个版本的主要原因(如果有的话)。

我什么也想不到。

with上下文管理器就是为了去掉第一个示例中的所有样板代码。此外,如果出现错误,它会释放资源,这是第一个示例所没有的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65906553

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档