在不使用 import os 的情况下列出目录中存在的文件名

问题描述 投票:0回答:2

我正在尝试创建一个程序,允许在 python 上创建新用户。但是,如果新配置文件的名称与旧配置文件的名称相同,则已创建的用户将被覆盖,这是因为创建了一个以所选用户名作为标题的新文本文件,因此新文本文件会替换旧文本文件。

由于我的系统限制,我无法使用

import os
,因此我需要一种替代方法来列出目录或子目录中存在的所有文件名,以便可以将它们与新用户名进行比较,并在以下情况下取消用户创建:具有该名称的文件已存在,以防止用户被覆盖。

我的代码片段:

new_username=str(input('Please choose a username : '))
new_password=str(input('Please choose a password : '))
print("Good Choice!")

title=new_username + '.txt'           #Creating title of the file
file=open(title,'w')                  #Creating the file
file.write(new_password)              #Adding password to the file
file.close()

print("User succesfuly created!!")

这部分一切运行良好,我只需要一种方法来防止它覆盖其他用户。

感谢您的宝贵时间:)

python file directory subdirectory
2个回答
0
投票

您可以使用

pathlib
检查特定文件是否存在

from pathlib import Path

...

title = new_username + '.txt'  # Creating title of the file
is_exists = Path(title).exists() 
if not is_exists:
    with open(title, 'w') as file:
        file.write(new_password)

0
投票

您可以使用原生的python open()函数,然后尝试以读取模式打开它。如果不存在,它会抛出异常,你可以捕获它,如果发生,则该文件不存在,一切正常。

这是示例代码:

new_username = str(input('Please choose a username: '))

title = new_username + '.txt'
try:
    open(title, 'r')
    print("Username already exists. Choose a different one.")
except FileNotFoundError:
    new_password = str(input('Please choose a password: '))
    print("Good Choice!")
    file = open(title, 'w')
    file.write(new_password)
    file.close()
    print("User successfully created!")

© www.soinside.com 2019 - 2024. All rights reserved.