Issue
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')
Solution
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.
Answered By - Nico Answer Checked By - Candace Johnson (WPSolving Volunteer)