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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…