How to catch error and stop using IF and ELSE statement? - python-3.x

Hello i am new to python programming. I am self learning by doing a project.
the code below is working fine, but i want to catch the exception if the condition is FALSE. i already have a statement to print if the directory is not there; and continue. I know i can make this code work by nesting the if statement.
but i dont want to do. i want to proceed to next line of code. when i run this as it is, i will get an error if the directory is missing.
import os
goToDir = open("URPsetup.dat","r")
goToDirPath = goToDir.read()
if (os.path.exists(goToDirPath))== True:
os.chdir(goToDirPath)
else: print("directory not found, please check file URPsetup.dat")
goToConfig = open("utility.dat", "r")
print(goToConfig.read())
i get this error message when the directory is not there. What i mean here is that, the directory i supplied in "URPsetup.dat" was incorrect. I did this on purpose to see if the code will stop at the else statement above. it will print the else statement, and continue on to show the error message below. how do i catch this error and stop?
directory not found, please check file URPsetup.dat
Traceback (most recent call last):
File "C:/Users/R82436/PycharmProjects/URP2017/prototype.py", line 9, in <module>
goToConfig = open("utility.dat", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'utility.dat'
directory not found, please check file URPsetup.dat
Process finished with exit code 1

I GUESS you're looking for this:
import sys
.
.
else:
print("directory not found, please check file URPsetup.dat")
sys.exit()
.
.
OR this will do just fine too:
# No need to import sys
.
.
else:
print("directory not found, please check file URPsetup.dat")
raise SystemExit(0)
.
.
That will do the trick ;)
And try to explain your problem properly next time, You aren't completely clear on what is it exactly that you want to do.

Related

Unable to run Porter5: generating `.flatpsi` file instead of `.psi`

I am trying to use Porter5 to run protein secondary structure prediction on a FASTA file containing a bunch of protein sequences. I am using a Linux machine.
For starters, I decided to try using the example file that gets downloaded along with Porter5, called 2FLGA.fasta. The command I used was the one I found on the GitHub page for Porter5 (https://github.com/mircare/Porter5/)
$ python3 Porter5.py -i example/2FLGA.fasta --cpu 4
I got the following error message:
sh: 1: /home/user/ncbi-blast-2.8.1+/bin/psiblast: not found
PSI-BLAST executed in 0.01s
wc: example/2FLGA.fasta.psi: No such file or directory
awk: cannot open example/2FLGA.fasta.psi (No such file or directory)
HHblits executed in 0.01s
Traceback (most recent call last):
File "/home/user/Porter5/scripts/process-alignment.py", line 37, in <module>
sequences = lines[0] = len(lines) - 1
IndexError: list assignment index out of range
Traceback (most recent call last):
File "Porter5.py", line 80, in <module>
flatpsi_ann = open(filename+".flatpsi.ann", "r").readlines()
FileNotFoundError: [Errno 2] No such file or directory: 'example/2FLGA.fasta.flatpsi.ann'
After PSI-BLAST, the Porter5 script is expecting an output file called 2FLGA.fasta.psi. I checked the example directory and it contains an output file called 2FLGA.fasta.flatpsi.
I'm not sure what to do here. I don't want to try modifying any of the Porter5 scripts to look for .flatpsi files instead of .psi files because I am a beginner at programming, and I don't want all hell to break loose by tampering with the code.
Could someone please help me with this? Any help is appreciated.
(There are a bunch of errors to negotiate with later but I'll see about those after dealing with the first one.)
I am the author of Porter5 and I generally recommend to open an issue straight on GitHub since I don't get any notification otherwise.
It looks like the path of psiblast is wrong (first line of your error message). You can check that with the following command:
$ ls /home/user/ncbi-blast-2.8.1+/bin/psiblast
Also, the path for the executable or the database of HHblits is wrong, or maybe both. You can check that as follow (within Porter5/):
$ cat scripts/config.ini
You can either edit scripts/config.ini or run the following command until Porter5 runs succesfully:
$ python3 Porter5.py -i example/2FLGA.fasta --cpu 4 --setup
(The .flatpsi is an intermediate file, it doesn't contain a valid representation if HHblits doesn't run succesfully)

FileNotFoundError even though file exist

when trying to open a file using wit open .. getting error that file doesn't exist.
I am trying to parse some txt files , when working localy it works with no issue, but the issue started when I am trying to connect to a network folder. the strange this is that is does see the file , but says its not found .
The Path I referring is '//10.8.4.49/Projects/QASA_BR_TCL_Env_7.2.250/Utils/BR_Env/Call Generator/results/Console_Logs/*' (this folder is full of txt files.
but I am still getting this error:
FileNotFoundError: [Errno 2] No such file or directory: 'Console_log_01-01-2019_08-17-56.txt'
as you see , it does see the needed file .
in order to get to this file I am parsing splitting the path the follwoing way :
readFile = name.split("/")[9].split("\\")[1]
because if I am looking on the list of my files I see them the following way :
['//10.8.4.49/Projects/QASA_BR_TCL_Env_7.2.250/Utils/BR_Env/Call Generator/results/Console_Logs\Console_log_01-01-2019_08-17-56.txt',
after splitting I am getting :
Console_log_01-01-2019_08-17-56.txt
and still it says the file is not found.
def main():
lines =0
path = '//10.8.4.49/Projects/QASA_BR_TCL_Env_7.2.250/Utils/BR_Env/Call Generator/results/Console_Logs/*'
files = glob.glob(path)
print ("files")
print ('\n')
print(files)
for name in glob.glob(path):
print (path)
readFile = name.split("/")[9].split("\\")[1]
print(readFile)
with open(readFile,"r") as file:
lines = file.readlines()
print (lines)
main()
files
['//10.8.4.49/Projects/QASA_BR_TCL_Env_7.2.250/Utils/BR_Env/Call Generator/results/Console_Logs\\Console_log_01-01-2019_08-17-56.txt', '//10.8.4.49/Projects/QASA_BR_TCL_Env_7.2.250/Utils/BR_Env/Call Generator/results/Console_Logs\\Console_log_01-01-2019_08-18-29.txt']
Traceback (most recent call last):
//10.8.4.49/Projects/QASA_BR_TCL_Env_7.2.250/Utils/BR_Env/Call Generator/results/Console_Logs/*
Console_log_01-01-2019_08-17-56.txt
File "C:/Users/markp/.PyCharmEdu2018.3/config/scratches/scratch_3.py", line 19, in <module>
main()
File "C:/Users/markp/.PyCharmEdu2018.3/config/scratches/scratch_3.py", line 16, in main
with open(readFile,"r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'Console_log_01-01-2019_08-17-56.txt'
Process finished with exit code 1
When you are looking for the file you are looking in the entire path, however when you are opening the file, you are referencing it as if it was in the local path, either change the current working directory with
os.chdir(path)
before opening the file, or in the open statement use
open(os.path.join(path,filename))
I recommend the first approach if you have to open only one file in your program and second if you open multiple files at multiple directories.
In future better format your questions, stack overflow has multiple tools, use them, also you can see how your text looks, make sure to have a look at it before posting. Use the code brackets for your code, that will help whoever is trying to answer.

Reading multiple files "except IOError as exc:"

I was looking through some example of how to read multiple files of data and come across these codes pop-up a lot:
try:
...
except IOError as exc:
if exc.errno != errno.EISDIR:
raise
But I couldn't see anyone trying to explain it so I was hoping if you guys can help me to understand what it is?
Here is an example:
import glob
import errno
...
#Create a list of the path of all .txt files
files_list = glob.glob(data_path)
#Iterate through the files in files_list
for file_name in files_list:
try:
#something
except IOError as exc:
if exc.errno != errno.EISDIR:
raise
Here, we'll go through these lines of code one by one.
except IOError as exc:
The above line just catches an exception and gets the error message in the variable exc. What the exception means is along the lines of
when a system function returns a system-related error, including I/O failures such as “file not found” or “disk full” (not for illegal argument types or other incidental errors). Python 3 Docs
Note in Python 3, this is now OSError as IOError is merged into it.
if exc.errno != errno.EISDIR:
This line will check the type of error. This is given by the error's errno attribute. Specifically, errno.EISDIR means the error given came because the 'file' was actually a folder / directory. More info can be found here :D.
raise
Now the if statement has gone through and checked the type of error. It only lets it through to the raise over here if the error type does NOT mean that the path given was a directory. This means the exception could mean anything from 'Permission Denied' to 'Out of Memory'.
Hope that helped you out :D

FileNotFoundError, even though the file exists

I've made a small program in Python that reads text files. However, I keep getting the FileNotFoundError, even though the file exists. The seemingly problematic code of my code looks like this:
fileEntered = False
while not fileEntered:
try:
fileName = input("Enter file name: ")
file = open(fileName, "r")
fileEntered = True
fileContents = file.readlines()
file.close()
except FileNotFoundError:
print("File not found. Please try again.")
When asked for the file, I enter randomtext.txt (which is located in the same folder as the program), but it keeps throwing the FileNotFoundError (it keeps printing the line in the except block).
Will be able to tell whether you are getting Win Error 2 or Win Error 3 when you are opening the file? If Win Error 2, then the problem may be related to your current working directory. That means, the scripting is looking into a different folder eventhough the file exists. If you are getting Win Error 3, then it is a different issue.
I've amended your code to get exact error code.
fileName = input("Enter file name: ")
file = open(fileName, "r")
fileContents = file.readlines()
print(fileContents)
file.close()
I am getting FileNotFoundError: [Errno 2] No such file or directory: '454544.txt' (when there is not file exists - Errno 2]. When I tried with full path or relative path, the script works fine. Please try and get the actual error so that you can progress. If the file exists in your current working directory, then the script will work properly. Please change the working directory to try.

Iam not quite sure how to define Users in this case

iam a total noob in python; i have a background in chemistry and iam doing my master in computational chemistry. Iam trying to learn computer science as fast as i can.
I currently dont know how to solve this error. I have googled the question but the answers dont actually satisfy.
I would really appreciate if you guys give me hints on how to fix this error.
Thanks,
Thanh Le
In order for the program to work, it uses codes from this file containing:
from RunRMSD import RunRMSD
RunRMSD()
from SumRMSD import SumRMSD
SumRMSD()
then it uses codes from a file (RunRMSD) containing:
run calcRMSD.py to get raw output from pymol
def RunRMSD():
# get output directory from a threefiles.txt
with open('./threefiles.txt') as fi:
fline = fi.readline()
flist = fline.split('\t')
path_output = flist[1]
import os
command = '/opt/local/bin/pymol -cqr '+'./CalcRMSD.py > '/Users/thanhle/Desktop/output/'RMSD.out'
os.system(command)
Not sure if my path is correct though.
thanhs-MacBook-Pro-2:untitled folder thanhle$ python Director_RMSD.py
Traceback (most recent call last):
File "Director_RMSD.py", line 5, in <module>
RunRMSD()
File "/Users/thanhle/Desktop/ftdock-2-dev2/untitled folder/RunRMSD.py", line 11, in RunRMSD
command = '/opt/local/bin/pymol -cqr '+'./CalcRMSD.py > '/Users/thanhle/Desktop/output/'RMSD.out'
NameError: global name 'Users' is not defined
The "command" variable is not well written:
command = '/opt/local/bin/pymol -cqr '+'./CalcRMSD.py > '/Users/thanhle/Desktop/output/'RMSD.out'
The error is thrown because the path /Users/thanhle/Desktop/output/ is not concatenated and also you are missing a apostrophe. If you don't want to parse any variable to the command it should be written:
command = '/opt/local/bin/pymol -cqr ./CalcRMSD.py > /Users/thanhle/Desktop/output/RMSD.out'

Resources