我正在尝试检查文件是否存在于 Linux Mint 的目录中,但收到错误

I'm trying to check to see whether a file exists in a directory on Linux Mint but recieve error

我正在尝试查看目录中是否存在文件,如果不存在,则创建它。我正在使用 Anaconda 和 Python 版本 3.7.4。但是,当我 运行 代码时,我收到错误 NameError: name 'found' is not defined。我正在使用 Visual Studio 代码,我对编程还很陌生!

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')

直接这样做会不会更容易?

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

如果不退出,上下文路径将直接创建文件,如果退出将以写入模式打开。

for 范围内创建的 found 变量,因此无法从其外部访问。

在 for 循环之前定义它,例如:

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')