Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Check if a file exists.
#1
I need to look for a file in this path:

Quote:pathToAnswersHW = '/home/pedro/' + termName[0] + '/' + theClass[0] + '/correctAnswersHW/'

but sometimes this file

Quote:theAnswersHW = open(pathToAnswersHW + 'correctAnswersHW' + theClass[0] + answersWeeknumber[0] + '.txt', 'r')

will not exist.

I think there must be some 'os.if_not_exists(file)' I can just return from the function.

What is the best way to check if the file exists?

def openAnswersHW():
    pathToAnswersHW = '/home/pedro/' + termName[0] + '/' + theClass[0] + '/correctAnswersHW/'
    # HW get the correct HW answers with answerDataHW = theAnswersHW.readlines()
    theAnswersHW = open(pathToAnswersHW + 'correctAnswersHW' + theClass[0] + answersWeeknumber[0] + '.txt', 'r')
    # check if the file exists
    
    #put a return in here if the file does not exist

    answerDataHW = theAnswersHW.readlines()
    theAnswersHW.close()
    # HW standardize the apostrophes
    aposSorted = changeApostrophe(answerDataHW)
    echoMessage('Apostrophes sorted ... ')
    for word in aposSorted:            
        answersHW.append(word)        
    echoMessage('answersHW is: ' + str(len(answersHW)) + ' long.')
    echoMessage('Now click "tidy student answers CW" or "tidy student answers HW"')
Reply
#2
It's pretty common to instead attempt the open and then catch if it fails due to nonexistence.

try:
    theAnswersHW = open(pathToAnswersHW + 'correctAnswersHW' + theClass[0] + answersWeeknumber[0] + '.txt', 'r')
except FileNotFoundError:
    return None # return immediately if file doesn't exist
# program continues here if open succeeds
Reply
#3
As @bowlofred explained - the canonic way is to try to open and handle the exception. Checking if file exists and then try to open it is prone to race condition - the file may be deleted/renamed between your check and your attempt to work with it.

As a side note - it's better using with context manager when open the file
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
Some style issues that make this not so good to look at(for a Python guy),it's Python you are writing and not Java Wink
To give a example with some cleaning done.
path_hw = f'/home/pedro/{term_name[0]}/{the_class[0]}/correct_hw/'
try:
    with open(f'{path_hw}correct_hw{the_class[0]}{week_number[0]}.txt', 'r') as answers_hw:
        data_hw = answers_hw.readlines()
except FileNotFoundError as error:
    print(error)
So f-string,no camlCase(in Python use snake_case) and with open as mention.
Using as as error we cacth what FileNotFoundError return.
Example:
Error:
[Errno 2] No such file or directory: 'data.txt'
Reply
#5
(Sep-08-2020, 05:58 AM)Pedroski55 Wrote: I think there must be some 'os.if_not_exists(file)' I can just return from the function.

Yes, of course there is.

import os

if os.path.exists('/directory/subdirectory/filename'):
     # do something 
else:
     # do something else
One can be more specific as well (is it a file?):

if os.path.isfile('/directory/subdirectory/filename'):
    # do something
else:
    # do something else
Of course, you can reverse it with 'not': if not os.path.isfile('/directory/subdirectory/filename'):

Always keep in mind buran's wise words about race condition.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#6
Thank you everyone! I am the wiser!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  please check this i wanna use a csv file as a graph xCj11 5 1,480 Aug-25-2022, 08:19 PM
Last Post: deanhystad
  check if a file exist on the internet and get the size kucingkembar 6 1,758 Apr-16-2022, 05:09 PM
Last Post: kucingkembar
  Code to check folder and sub folders for new file and alert fioranosnake 2 1,931 Jan-06-2022, 05:03 PM
Last Post: deanhystad
  Check last time file was accessed Pavel_47 4 2,822 Jun-01-2021, 05:47 PM
Last Post: Yoriz
  How to check if a file has finished being written leocsmith 2 7,819 Apr-14-2021, 04:21 PM
Last Post: perfringo
  pathlib destpath.exists() true even file does not exist NaN 9 4,653 Dec-01-2020, 12:43 PM
Last Post: NaN
  How to check to see a dbf file is EOF ? DarkCoder2020 0 1,719 Jun-16-2020, 05:03 PM
Last Post: DarkCoder2020
  p]Why os.path.exists("abc/d") and os.path.exists("abc/D") treat same rajeev1729 1 2,160 May-27-2020, 08:34 AM
Last Post: DeaD_EyE
  Building a script to check size of file upon creation mightyn00b 2 2,383 Apr-04-2020, 04:39 AM
Last Post: Larz60+
  Shutil move if file exists in destination Friend 2 6,752 Feb-02-2020, 01:45 PM
Last Post: Friend

Forum Jump:

User Panel Messages

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