0

I am trying to print out the full text of a text file. But if that text file does not exist, I want it to print that it does not exist, otherwise it wont let the rest of the code work.

Printing out only the text files works

for x in ABC:
    print(f"{x}:")
    with open("./" + x + "/Log.txt") as f:
    print(f.read())

However, when I am trying to see if that file is found, I get an error. This is how I tried to do it (it is wrong)

for x in ABC:
    print(f"{x}:")
    with open("./" + x + "/Log.txt") as f:
        if f.empty:
            print("No files found.")
        else:
            print(f.read())
QueenBee
  • 107
  • 1
  • 9

2 Answers2

1

The best way is this:

for x in ABC:
    print(f"{x}:")
    try:
        with open(f"./{x}/Log.txt") as f:
            print(f.read())
    except FileNotFoundError:
        print("File does not exist")

Checking beforehand leaves your code open to race conditions, where a file is deleted after you check it's existence but before you try to open it.

Jasmijn
  • 9,370
  • 2
  • 29
  • 43
0

First check if the file exists, and if it does print the contents; otherwise say it doesn't exist:

import os

filename = 'foo.txt'

if os.path.isfile(filename):
    with open(filename, 'r') as f:
        print(f.read())
else:
    print(filename + ' does not exist.')
PApostol
  • 2,152
  • 2
  • 11
  • 21