Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

python - Temporarely open a file to use its content as input: with-statement or redirect sys.stdin?

Let's say for instance I would want to write a function that gets some basic input from a .txt file, say some numbers, and I want to print on another .txt file those numbers multiplied by 2.

I was taught I can import sys and redirect sys.stdin and sys.stdout to those files, as such

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('
') #just to keep each line divided
        
    sys.stdin.close()
    sys.stdout.close()
    sys.stdin=origin
    sys.stdout=origout

Everything works just fine, but then I realized I'm importing a library, redirecting the standard input and standard output to the right files, just to redirect them right away back to what they were originally.

That's when the with statement came to my mind. Here's the exact same function but I'm using with instead of the whole stdin and stdout redirection idea.

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('
')

Which to my eyes looks a lot less clunky.

I was wondering what are the main reasons (if there is any) why I should prefer the first version over the second. Thank you.

question from:https://stackoverflow.com/questions/65906553/temporarely-open-a-file-to-use-its-content-as-input-with-statement-or-redirect

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I was wondering what are the main reasons (if there is any) why I should prefer the first version over the second.

I can't think of any.

The with context manager is there precisely to get rid of all the boiler plate code from your first example. PLUS, it releases the resource if there's an error, which is something the first example doesn't have.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...