我如何创建名称是从用户输入的python文件,例如,如果创建了名为abc的用户输入“ abc”文件?请帮助我,我想创建文件。我不知道是什么原因造成的。我尝试了其他方法,但是它不起作用,这个问题与其他问题有所不同,因为我想创建用户想要的文件。
def admin():
p=open("password.txt","r")
a=p.read()
p.close()
password=input("Enter a Password: ")
if password==a:
print("Log In Successfull")
print("Press 1 to view current categories of Item.")
print("Press 2 to add new category. ( will include Name of category)")
print("Press 3 to add product to category.")
print("Press 4 to view a specific product")
print("Press 5 to delete a product.")
print("Press 6 to view view all orders purchased")
print("Press 7 to view purchase record of a specific customer by entering Nameas search criteria.")
choice=int(input())
if choice==1:
p=open("categories.txt","r")
if p.mode=="r":
contents=p.read()
print(contents)
if choice==2:
categories=[]
data=[]
print("Add product in a categore")
category=input("Enter Name of category: ")
name=input("Enter Name of product: ")
price=int(input("Enter Price of a Product: "))
quantity=int(input("Enter Quantity of a product: "))
data.append(category)
data.append(name)
data.append(quantity)
data.append(price)
print(data)
categories.append(data)
p=open("categories.txt","a+")
for i in categories:
for j in data:
p.write(str(j))
p.write("\n")
p.close()
else:
print("invalid Password")
num=int(input("Press 1 to change password."))
if num==1:
n=(input("Type New Password: "))
p=open("password.txt","w")
p.write(n)
print("New Password is: ",n)
while True:
print("Select the following.")
print("1. Admin")
print("2. Customer")
print("3. Quit")
n=int(input())
if n==1:
admin()
if n==3:
print("Good Bye. ")
break
请帮助我
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
在您的代码中,您想要根据用户的输入创建一个文件。这里是一个修改版的函数,它会根据用户输入的名称创建一个Python文件:
def create_file_from_user_input():
file_name = input("Please enter the name of the Python file you want to create (include '.py' at the end): ")
try:
with open(file_name, "w") as file:
file.write("# This is a new Python file created by your request.\n")
print(f"File '{file_name}' has been created successfully.")
except IOError as e:
print(f"An error occurred while creating the file: {e}")
# Example usage:
create_file_from_user_input()
这个函数首先提示用户输入他们想要创建的文件名(确保用户包括.py
扩展名),然后尝试打开并写入一行示例文本到该文件中。如果文件创建成功,它会通知用户;如果有错误发生(比如权限问题或磁盘满),则会捕获异常并打印错误信息。
请注意,这段代码是独立于您提供的原始代码的。如果您想将此功能整合进您的现有程序中,请根据需要调整调用时机和逻辑。