如果目录为空则不创建新文件

Not Creating New File If Empty Directory

好的,我正在使用我最喜欢的两个模块创建我的 Python 项目。烧瓶和不和谐。现在可以说,我不是最好的,但是当目录为空时,我在尝试创建新文件时遇到了一个新错误。这是我收到的错误:


2.168.0.26 - - [18/Jun/2021 21:30:42] "GET / HTTP/1.1" 404 -
Trying to open Mewniverse's folder
File not found error raised
File not accessible. creating new.
[2021-06-18 21:30:42,559] ERROR in app: Exception on /favicon.ico [GET]
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/flask/app.py", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/flask/app.py", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/flask/app.py", line 1513, in full_dispatch_request
    rv = self.dispatch_request()
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/flask/app.py", line 1499, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "<string>", line 53, in hello_world
OSError: [Errno 30] Read-only file system: '/Mewniverse'
192.168.0.26 - - [18/Jun/2021 21:30:42] "GET /favicon.ico HTTP/1.1" 500 -

现在这是我的代码(忽略缩进和未完成的部分,因为它还有很多未完成的部分):


def hello_world(ID):
    print(f"Trying to open {ctx.author.name}'s folder")
    directory = f'/{ctx.author.name}'
    parent_dir = 'userFiles/templates'
    path = os.path.join(parent_dir, directory)

    if os.path.isfile(path):
        print ("File exist")
    else:
        print(f'File not found error raised')
        print("File not accessible. creating new.")
        f = open(path, "w")
        f.write("Now the file has more content!")
        f.close()
        print("Directory created and written in")

    return render_template(f'{ctx.author.name}.html')
        
    
app.run(host='0.0.0.0', port=8080)
            
        
await ctx.message.channel.send(f'Here you go {ctx.author.name}! Your site will be here: http://192.168.0.26:8080/{ctx.author.name}')

我被困在这里几个小时了,所以我希望有人能帮助快速找到解决方案。可以的话谢谢了。

评论回复:

How are you executing the script? Are you calling it directly, or via a service or something? Because when calling a script as a service, you need to give the absolute path to the files you want to work with. If your OS thinks that path is an absolute path, it will try to access something with very high privileges on the file tree, which might cause the problem. – itzFlubby

早上 5 点,我需要睡觉。所以我只是把答案抄下来让大家明白这是解决办法。非常感谢 <3