Python Forum
Getting a "Cannot be Opened"" error Message
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Getting a "Cannot be Opened"" error Message
#1
Hi Folks,
I'm having a "Cannot opened" error message even though i have the file in my directory. below is my code which consist of reading a file and determining the average game won.


Quote:
#! /usr/bin/python3
def team_average(filename):
        numberOfGames = 0
        soxWins = 0
        try:
                file = open(filename, 'r')
                for line in file:
                        numberOfGames += 1
                        game = line.split()
                        scores = game[1]
                        scores_list = scores.split('-')
                        for score in scores_list:
                                if int(score[0]) - int(score[1]) > 0:
                                        soxWins += 1
                average_win = int(s0xWins/numberOfGames) * 100
        except:
                print (filename, "Cannot be opened")

team_average('xxxxx')
print(team_average('red_sox.txt'))
Quote:# This is my output (which is not what i was expecting )

xxxxx Cannot be opened
red_sox.txt Cannot be opened
None


Please what did i get wrong ?
Best,
valerydolce

Below is the content of the "red_sox.txt" file

2011-07-02      Red Sox @  Astros       Win 7-5
2011-07-03      Red Sox @  Astros       Win 2-1
2011-07-04      Red Sox vs Blue Jays    Loss 7-9
2011-07-05      Red Sox vs Blue Jays    Win 3-2
2011-07-06      Red Sox vs Blue Jays    Win 6-4
2011-07-07      Red Sox vs Orioles      Win 10-4
2011-07-08      Red Sox vs Orioles      Win 10-3
2011-07-09      Red Sox vs Orioles      Win 4-0
2011-07-10      Red Sox vs Orioles      Win 8-6
2011-07-15      Red Sox @  Rays         Loss 6-9
2011-07-16      Red Sox @  Rays         Win 9-5
2011-07-17      Red Sox @  Rays         Win 1-0
2011-07-18      Red Sox @  Orioles      Win 15-10
2011-07-19      Red Sox @  Orioles      Loss 2-6
2011-07-20      Red Sox @  Orioles      Win 4-0
2011-07-22      Red Sox vs Mariners     Win 7-4
2011-07-23      Red Sox vs Mariners     Win 3-1
2011-07-24      Red Sox vs Mariners     Win 12-8
2011-07-25      Red Sox vs Royals       Loss 1-3
2011-07-26      Red Sox vs Royals       Win 13-9
2011-07-27      Red Sox vs Royals       Win 12-5
2011-07-28      Red Sox vs Royals       Loss 3-4
2011-07-29      Red Sox @  White Sox    Loss 1-3
2011-07-30      Red Sox @  White Sox    Win 10-2
2011-07-31      Red Sox @  White Sox    Win 5-3
Reply
#2
what OS?
What are the file permissions?
Shouldn't matter because if you can list it, you should be able to list it.

Try the following.
add
import os
...
print('Current working directory: {}'.format(os.getcwd())
Reply
#3
This is example how not to implement try/except - you catch all exceptions and provide a message that's not relevant.

you have s0xWins note that second character is zero, not o on line

average_win = int(s0xWins/numberOfGames) * 100
So your actual error is that s0xWins is used before assignment.

You should avoid using such catch-all exception clause, especially when you don't pass on the actual error description.
Reply
#4
It's on a linux host that i access remotely. 
below are the permissions
Quote:total 3
-rwxr-xr-x 1 psimo it117-1G  602 Feb  9 05:57 hw2.py
-rw-r--r-- 1 psimo it117-1G 1214 Feb  3 21:07 red_sox.txt
Reply
#5
(Feb-09-2017, 11:26 AM)valerydolce Wrote: It's on a linux host that i access remotely. 
below are the permissions
Quote:total 3
-rwxr-xr-x 1 psimo it117-1G  602 Feb  9 05:57 hw2.py
-rw-r--r-- 1 psimo it117-1G 1214 Feb  3 21:07 red_sox.txt
This is irrelevant. See buran's answer. Your try/except is catching all errors, and the code wrongly assumes that they can only mean that the file cannot be opened. In that case the exception comes from an error in your code... You should only be catching exceptions of type IOError, so that errors from your code are duly reported.
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#6
buran got it right, the error causes an exception so the code doesn't complete
Reply
#7
Buran/oFnuts,
Per your advise, I changed the code as shown below and i got a bunch of error
def team_average(filename):
        numberOfGames = 0
        soxWins = 0
        try:
                file = open(filename, 'r')
        except:
                print (filename, "Cannot be opened")
        else:
                for line in file:
                        numberOfGames += 1
                        game = line.split()
                        scores = game[1]
                        scores_list = scores.split('-')
                        for score in scores_list:
                                if (int(score[0]) - int(score[1]) > 0:
                                        soxWins += 1
                average_win = int(soxWins/numberOfGames) * 100

team_average('xxxxxx')
print(team_average('red_sox.txt'))
and below is the error i got :
Quote:Traceback (most recent call last):
  File "./hw2.py", line 25, in <module>
    print(team_average('red_sox.txt'))
  File "./hw2.py", line 20, in team_average
    if int(score[0]) - int(score[1]) > 0:
ValueError: invalid literal for int() with base 10: 'R'
Reply
#8
You need a closing parenthesis:
                if (int(score[0]) - int(score[1])) > 0:
also, can't do this:
  try:
      file = open(filename, 'r')
  except:
      print (filename, "Cannot be opened")
  else:
and finally you're indentation seems all messed up

I take the last bit back, you can have an else clause - but it's not being used properly here
Reply
#9
I did but it still returned the same error !

Regarding the indentation, i'm using the tabulation key instead of space.
Reply
#10
def team_average(filename):
    numberOfGames = 0
    soxWins = 0
    try:
        with open(filename, 'r') as file:
            for line in file:
                numberOfGames += 1
                game = line.split()
                scores = game[1]
                scores_list = scores.split('-')
                print('scores_list: {}'.format(scores_list))
                for score in scores_list:
                    if (int(score[0]) - int(score[1])) > 0:
                        soxWins += 1
                    average_win = int(soxWins / numberOfGames) * 100

                    team_average('xxxxxx')
                    print(team_average('red_sox.txt'))
    except:
        print(filename, "Cannot be opened")

team_average('red_sox.txt')
This is why print statements are so useful

results:
Output:
C:\Python35\python.exe M:/python/e-h/f/forum/misc4.py scores_list: ['Red'] red_sox.txt Cannot be opened
  • because score has 'Red' in it, it causes an exception (but not a file exception)
  • The exception is caught, but displays the wrong message (becuase not being qualified)

adding one more print statement makes the problem very clear:
def team_average(filename):
    numberOfGames = 0
    soxWins = 0
    try:
        with open(filename, 'r') as file:
            for line in file:
                numberOfGames += 1
                game = line.split()
                print('game: {}'.format(game))
                scores = game[1]
                scores_list = scores.split('-')
                print('scores_list: {}'.format(scores_list))
                for score in scores_list:
                    if (int(score[0]) - int(score[1])) > 0:
                        soxWins += 1
                    average_win = int(soxWins / numberOfGames) * 100

                    team_average('xxxxxx')
                    print(team_average('red_sox.txt'))
    except:
        print(filename, "Cannot be opened")

if __name__ == '__main__':
    team_average('red_sox.txt')
result:
Output:
game: ['2011-07-02', 'Red', 'Sox', '@', 'Astros', 'Win', '7-5'] scores_list: ['Red'] red_sox.txt Cannot be opened
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Error message about iid from RandomizedSearchCV Visiting 2 1,008 Aug-17-2023, 07:53 PM
Last Post: Visiting
  does not save in other path than opened files before icode 3 899 Jun-23-2023, 07:25 PM
Last Post: snippsat
  Another Error message. the_jl_zone 2 974 Mar-06-2023, 10:23 PM
Last Post: the_jl_zone
  Mysql error message: Lost connection to MySQL server during query tomtom 6 15,998 Feb-09-2022, 09:55 AM
Last Post: ibreeden
Question How to get html information from a tab of my default browser opened with webbrowser? noahverner1995 2 4,466 Jan-14-2022, 10:02 AM
Last Post: noahverner1995
  understanding error message krlosbatist 1 1,904 Oct-24-2021, 08:34 PM
Last Post: Gribouillis
  Error message pybits 1 40,131 May-29-2021, 10:26 AM
Last Post: snippsat
  Rmarkdown opened by python code - errors Rav013 0 2,085 Apr-27-2021, 03:13 PM
Last Post: Rav013
  f-string error message not understood Skaperen 4 3,330 Mar-16-2021, 07:59 PM
Last Post: Skaperen
  Overwhelmed with error message using pandas drop() EmmaRaponi 1 2,360 Feb-18-2021, 07:31 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020