-2

I am using this in Python 3.6:

filetest="test.txt"
with open(filetest,"r") as file:

How should I make Python console to display "File not available" as an output if no input on the filetest is detected? (such as there is no test.txt in the directory)

3
  • 2
    Put a try/except block or check the presence of the file before hand using os or path module Commented Aug 17, 2020 at 5:22
  • Add try/except block and also catch FileNotFoundError if the file you want to read is not exists. Catch a bare exception is not a good habit for all programming language. Commented Aug 17, 2020 at 5:29
  • 'test.txt' is a string with a file name, test.txt is the attribute txt of the object test. Commented Aug 17, 2020 at 5:43

3 Answers 3

2

You can just wrap it in a try-except block, and if there is no file named "test.txt" then you will print the message: "File not available".

A simple example is:

filename="test.txt"
try:
    with open(filetest,"r") as file:
        pass
except OSError as e:
    print("File not available")
    print(e.strerror)

I added the OSError because it indicate problem in file handling where you can read about in the following link: https://docs.python.org/3/library/exceptions.html

One can also use the FileNotFoundError exception.

Sign up to request clarification or add additional context in comments.

6 Comments

You need something in the with block (even just a pass if you don't need to use the file) to make this syntactically legal.
Blank except clauses aren’t necessarily something to encourage ... perhaps be more specific with the except clause ... here you’ll happily catch all sorts of other errors in the with block
@ShadowRanger correct, originally I has a print which want added to the answer!
@donkopotamus You are right, added the OSError exception and added a link for the user to read about built-in exceptions
The broader exception is good. You could except OSError as e: and then print(e.strerror) so that you don't mask a different problem with an assumed no-such-file.
|
2

use try-except a simple sample has given below:

filename = 'test.txt'
try:
    with open(filename,"r") as file:
        read_file = file.read()

except FileNotFoundError:
    print("File not found")

Comments

1

Try-except blocks are what you look for.

try:
    filename=test.txt
    with open(filetest,"r") as file:
        print('File is available')
except EnvironmentError: # any IOError or OSError will be captured
    print('File not available')

1 Comment

The exception clause is very “wide” ... catching exceptions that may have nothing to do with opening the file ... for example, the current code will have an error before you even attempt to open the file ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.