Python KeyError: 'OUTPUT_PATH' - python

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.

A KeyError means that an element doesn’t have a key. So that means that os.environ doesn’t have the key 'OUTPUT_PATH'.

Simply, change the path of the python code to your local path.
fptr = open("./result.output", 'w')

Hackerrank sends output to a file, but for practice locally, the output can be printed.
You can remove the use of ftpr by commenting out these lines
fptr = open(os.environ['OUTPUT_PATH'], 'w') and
fptr.close()
And replace line fptr.write(str(result) + '\n') with print(str(result) + '\n')

change your code like this:
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
n = int(input())
result = maximumDraws(n)
print(str(result) + '\n')

Related

Cannot write in a file when using starting a program using the console

I've started Python recently, and I want to create a program which read a calculation in a file, execute it (using the eval() function) and write the result in another file. This program must be started with the console.
I've created the program, which works perfectly when I start it by double clicking it. But when I start the program with the console, it doesn't write the result in the file, and I don't get any errors. I know the calculation has been done, because the result is written in the console.
I've tried by running the program with .py extension, and compiling it to an executable, using pyinstaller. They work with a double-click, but not from the console.
Here are the commands I used to run the programs :
F:\Path\To\App\calculator.exe
C:\Path\To\Python\python.exe F:\Path\To\App\calculator.py
The code I use to read, evaluate and write the calculation
input = open('calcul.txt', 'r')
output = open('result.txt', 'w')
calcul = input.read()
print(calcul)
print(eval(calcul).toString())
output.write(eval(calcul).toFileString())
input.close()
output.close()
def toString(self):
number = str (round(self.m_number, 4))
number_scientific = str(format(self.m_number, ".3E"))
imprecision = str (round(self.m_imprecision, 4))
imprecision_scientific = str(format(self.m_imprecision, ".3E"))
relative_imprecision = str(round(self.m_relative_imprecision * 100, 2))
return "\t Number \t\t= " + number + " \t= " + number_scientific + "\n\t Imprecision \t\t= " + imprecision + " \t= " + imprecision_scientific + "\n\t Relative Imprecision \t= " + relative_imprecision + "%\n\t"
def toFileString(self):
return str (round(self.m_number, 4)) + '\n' + str (round(self.m_imprecision, 4))
When I run the console as administrator, I have that:
C:\WINDOWS\system32>F:\Users\Ludovic\Desktop\Apprentissage\C++\Qt\calculator\python_calculator\calculator.exe
Traceback (most recent call last):
File "calculator.py", line 376, in <module>
calcul = input.read()
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\WINDOWS\\system32\\calcul.txt'
[26580] Failed to execute script calculator
C:\WINDOWS\system32>C:\Users\Ludovic\AppData\Local\Programs\Python\Python38\python.exe F:\Users\Ludovic\Desktop\Apprentissage\C++\Qt\calculator\python_calculator\calculator.py
Traceback (most recent call last):
File "F:\Users\Ludovic\Desktop\Apprentissage\C++\Qt\calculator\python_calculator\calculator.py", line 373, in <module>
input = open('calcul.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'calcul.txt'
Run console as administrator
Add path tou your input and output files
input = open('your_path_to_file\\calcul.txt', 'r')
output = open('your_path_to_file\\result.txt', 'w')
Or put files in script folder and then call them like this
import sys
input = open(sys.path[0]+'\\calcul.txt', 'r')
output = open(sys.path[0]+'\\result.txt', 'w')
Update
for unversal file path for .exe and .py try this (files should be in .exe and .py folder)
import sys
if getattr(sys, 'frozen', False):
application_path = ''
else:
application_path = sys.argv[0]+'\\'
input = open(application_path+'calcul.txt', 'r')
output = open(application_path+'result.txt', 'w')
Maybe you are not in the directory you wished write your txt file for exemple:
if you are here in the cmd: MyFolder\
and you execute your python file by writting: python MyFolder\Python_prog\program.py
the .txt file will be written in MyFolder\ not in MyFolder\Python_prog\
I'm not sure because I've never tried out with python but I had the same kind of Errors with JavaScript

Python script, no output?

I have written a simple python script to hash a file and output the result. However, when I run the script (python scriptname.py), I don't get any output (expected it to print the checksum). I don't get any errors from the console either.
What am I doing wrong?
#!/usr/bin/env python
import hashlib
import sys
def sha256_checksum(filename, block_size=65536):
sha256 = hashlib.sha256()
filename = '/Desktop/testfile.txt'
with open(filename, 'rb') as f:
for block in iter(lambda: f.read(block_size), b''):
sha256.update(block)
return sha256.hexdigest()
def main():
for f in sys.argv[1:]:
checksum = sha256_checksum(f)
print(f + '\t' + checksum)
if __name__ == '__main__':
main()
def main():
for f in sys.argv[1:]:
The script expected arguments. If you run it without any arguments you don't see any ouput.
The main body suppose that you provide list of files for hashing but in hashing function you hardcoded
filename = '/Desktop/testfile.txt'
So, if you want to pass files for hashing as script arguments remove the line
filename = '/Desktop/testfile.txt'
and run
python scriptname.py '/Desktop/testfile.txt'

Python File not opening file?

So I have this code, and I am trying to have it open a file. However, the exception part of the code always gets executed.
def main():
#Opens up the file
try:
fin = open("blah.txt")
independence = fin.readlines()
fin.close()
independence.strip("'!,.?-") #Gets rid of the punctuation
print independence
#Should the file not exist
except:
print 'No, no, file no here'
if __name__ == "__main__":
main()
I checked to see if the file name was spelled correctly, and it was, and the file is in the same directory as the python file, and I've used this code before. Why is it not working?
independence is a list of strings. You can't call strip on a list.
Try this:
def main():
fin = open('blah.txt', 'r')
lines = fin.readlines()
fin.close()
for line in lines:
print line.strip("'!,.?-")
if __name__ == '__main__':
try:
main()
except Exception, e:
print '>> Fatal error: %s' % e

Converting a python code for Mac to Windows

I am new to python and I have a question about a piece of python code that creates a cleaned up output file from a model output file. This code was written for a Mac user, but now I want to run it in Windows. But it gives an error message. Could you help me in converting this code so I can use it in Windows? Thanks.
import sys
if len(sys.argv) > 1:
fileName = sys.argv[1]
else:
print "selected_um_b.out" #insert file name here
sys.exit()
f = open(fileName)
counter = 0
fw = open(fileName+".cleaned", 'w')
for line in f:
line = line.strip()
counter = counter + 1
if counter <= 4:
fw.write(line+"\n");
continue
values = line.split("\t")
if (values[4].strip() == "-99" or values[5].strip() == "0"): continue
fw.write("\t".join(values)+"\n")
f.close()
Update
The error message is:
Traceback (most recent call last): File
"C:\trial_batch\clean_output.py", line 7, in sys.exit()
SystemExit
The program expects a filename on the command line when you execute it. It appears you did not provide one, so the program exited (the sys.exit() call terminates the program).
How are you trying to use it? If you just want to convert one file, put the file and the Python script into the same directory. Replace lines 3 through 7 with filename = "yourfilename.typ" (do not indent the line); it will read the file ("yourfilename.typ" in my example) and write an output file with 'cleaned' in the filename.

how to create file names from a number plus a suffix in python

how to create file names from a number plus a suffix??.
for example I am using two programs in python script for work in a server, the first creates a file x and the second uses the x file, the problem is that this file can not overwrite.
no matter what name is generated from the first program. the second program of be taken exactly from the path and file name that was assigned to continue the script.
thanks for your help and attention
As far as I can understand you, you want to create a file with a unique name in one program and pass the name of that file to another program. I think you should take a look at the tempfile module, http://docs.python.org/library/tempfile.html#module-tempfile.
Here is an example that makes use of NamedTemporaryFile:
import tempfile
import os
def produce(text):
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
f.write(text)
return f.name
def consume(filename):
try:
with open(filename) as f:
return f.read()
finally:
os.remove(filename)
if __name__ == '__main__':
filename = produce('Hello, world')
print('Filename is: {0}'.format(filename))
text = consume(filename)
print('Text is: {0}'.format(text))
assert not os.path.exists(filename)
The output is something like this:
Filename is: /tmp/tmpp_iSrw.txt
Text is: Hello, world

Categories