-1

I am attempting to see whether a file exists within a directory then if it doesn't exist, create it. I'm using Anaconda and Python version 3.7.4. However when I run the code I recieve the error NameError: name 'found' is not defined. I'm using Visual Studio Code and am quite new to programming!

import fnmatch

import os

print()
for file in os.listdir('/home/user/CI6724_J0874321_John/'):
    if fnmatch.fnmatch(file, 'CI5232_Logs.txt'):
        found = True

if found:
    print('File exists')
else:
    open('/home/user/CI6724_J0874321_John/', 'w')
meshkati
  • 1,720
  • 2
  • 16
  • 29
  • The short answer is that is not how you check for a file. The longer answer is in the link. – Jared Smith Jan 20 '21 at 12:51
  • A few notes: you repeat `'/home/user/CI6724_J0874321_John/'`, define it once as a variable. `open('/home/user/CI6724_J0874321_John/', 'w')` will attempt to open a directory, which will fail. `found` may be not defined if the `if` branch is not executed (as pointed by meshkati's answer). – Jan Stránský Jan 20 '21 at 12:51

2 Answers2

0

wont be easier to do directly this?

with open("/home/user/CI6724_J0874321_John/CI5232_Logs.txt", "w") as f:
    # rest of the code..

The context path will create the file directly if not exit and if exits will be open in writing mode.

Nico
  • 309
  • 1
  • 3
  • 18
  • How does it answer the question? – Jan Stránský Jan 20 '21 at 12:45
  • Maybe OP is not familiar with contexts path. – Nico Jan 20 '21 at 12:46
  • the OP has several problems, (`found` variable, opening a directory for writing..), replacing "plain old open" with `with` is the least problem IMO.. but for sure `with open` is preferable – Jan Stránský Jan 20 '21 at 12:49
  • I’ve now solved the found issue! Thank you all for your help. Whereabouts would the with open, go in the code & what would it replace? Thank you again! I’ve only started Python recently – Number_S1x Jan 20 '21 at 15:15
  • Nice, well [context managers](https://book.pythontips.com/en/latest/context_managers.html) save a lot of work, I will recommend to use it when opening files. – Nico Jan 22 '21 at 13:39
0

The found variable created within the for scope, so it's not accessible from outside of it.

Define it before your for loop, like:

import fnmatch

import os

found = False

print()
for file in os.listdir('/home/user/CI6724_J0874321_John/'):
    if fnmatch.fnmatch(file, 'CI5232_Logs.txt'):
        found = True

if found:
    print('File exists')
else:
    open('/home/user/CI6724_J0874321_John/', 'w')
meshkati
  • 1,720
  • 2
  • 16
  • 29
  • This solved the problem! Thank you I now receive the error IsADirectoryError: [Errno21] Is a directory: ‘/home/user...’ – Number_S1x Jan 20 '21 at 15:16