【问题标题】:How to create text files with specific names and access to them如何创建具有特定名称的文本文件并访问它们
【发布时间】:2020-12-02 17:23:08
【问题描述】:

我正在创建一个项目,其中我有一个登录系统(非常基本),然后我需要创建具有特定名称的不同 txt 文件,例如:T1、T2、T3... 然后可以访问每个 txt文件并重置其中的数据。

这基本上是一个餐厅软件,其中用户使用名称登录,然后继续为某个表号创建文件。在那个 txt 文件中,我计划将账单保存为字符串代码和附加的价格。

到目前为止,我知道如果您open() 一个不存在的文件,它将被创建。

while True:
    action = input ('''
 - NEW table
    \n - ADD table
    \n - BILL
    \n - ... ''')

    if action.lower() == 'new':
        t = open('T.txt', 'w')


    elif action.lower() == 'add':
        table = input ('Select desired table number')

    elif action.lower() == "exit":
        exit()

第二个elif 是我计划使用用户输入选择所需文件的地方。

完整代码:

with open('names.txt', 'r') as r :
    f_n = r.read().splitlines()
print("Welcome to NAME.app")
##############
# USER LOGIN #
##############
while True:
    name = input("""
    \n - Insert name to logg in
    \n - ADD to save new user
    \n - LIST to see saved users
    \n - REMOVE to delete a user
    \n - EXIT to finish
    \n - ...""")

    lname = name.lower()

    if lname == "add":
        n_input = input("Name:")
        with open('names.txt', 'a') as f:
            f.write(n_input + '\n')

    elif lname == "list":
        with open('names.txt') as f:
            print(f.read().splitlines())
            f.close()

    elif name in f_n:
        print("Logged as", name.upper())
        input('Welcome, press enter to continue \n')
        break

    elif lname == 'remove':
        rem = input("Insert user name to remove \n ...")
        with open('names.txt', 'r+') as f:
            l = f.readlines()
            l = [z for z in l if rem not in z]
        with open('names.txt', 'w') as f:
            f.writelines(l)

    elif lname == "exit":
        exit()
####################
# TABLE MANAGEMENT #
####################
while True:
    action = input ('''
 - NEW table
    \n - ADD table
    \n - BILL
    \n - ... ''')

    if action.lower() == 'new':
        t = open('T.txt', 'w')


    elif action.lower() == 'add':
        table = input ('Select desired table number')

    elif action.lower() == "exit":
        exit()

谢谢。

【问题讨论】:

    标签: python python-3.x data-structures


    【解决方案1】:

    我不确定这是否可行,但如果您放置一个文本以外的变量,例如:' name = “T1.txt”' 和 next ' f = open(name, “w+”) '。 接下来(如果此代码有效)您可以创建一个函数来创建新名称(变量)

    【讨论】:

    • if action == 'new' : name = 'T1.txt' t = open(name, 'w') print('Done') 确实有效!!!
    【解决方案2】:

    通过 SkiBoxing 找到的解决方案是创建一个 变量,其中 输入 文件(表格)将是该数字。接下来是另一个变量,它结合了字符串 'T'input 数字。结果你总是得到:T(input).txt

    if action == 'new' :
            tn = input('Insert table number \n - ...')
            name = 'T' + tn
            t = open(name + '.txt', 'w+')
            print('Done')
    

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 1970-01-01
      • 2017-01-06
      • 1970-01-01
      • 2012-10-31
      相关资源
      最近更新 更多