I'm trying to run the following python code for to exercise
#!/bin/python3
import os
import sys
#
# Complete the maximumDraws function below.
#
def maximumDraws(n):
return n+1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
result = maximumDraws(n)
fptr.write(str(result) + '\n')
fptr.close()
but i get this error message
Traceback (most recent call last):
File "maximumdraws.py", line 13, in <module>
fptr = open(os.environ['OUTPUT_PATH'], 'w')
File "/home/inindekikral/anaconda3/lib/python3.6/os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'OUTPUT_PATH'
My Operation System is Linux Mint 19 Cinnamon. What i have to do?
I'm sure there are other ways to do this, but for Hackerrank exercises, the file pointer was opened this way:
fptr = open(os.environ['OUTPUT_PATH'], 'w')
... and I want it to just go to standard output.
I just changed that line to
fptr = sys.stdout # stdout is already an open stream
and it does what I want.
Note that on the one hand, os.environ['OUTPUT_PATH']
is a string, while fptr
is a stream/file pointer.
Variations:
If you want to write to a file, you can do it the way suggested above (setting the OUTPUT_PATH
environment variable).
Or, you can set the os.environ directly in python, e.g.
os.environ['OUTPUT_PATH'] = 'junk.txt' # before you open the fptr!
os.environ lets you access environment variables from your python script, it seems you do not have an environment variable with name OUTPUT_PATH. From the terminal you run your python script, before running your python code set an environment variable with name OUTPUT_PATH such as:
export OUTPUT_PATH="home/inindekikral/Desktop/output.txt"
Your python script will create a file at that location.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With