Сохранить текстовые файлы из списка - PullRequest
0 голосов
/ 27 сентября 2019

Список проектов

Если вы не понимаете, попробуйте скопировать этот код, чтобы помочь мне, я новичок в Python, поэтому я начинаю с этого проекта: создатель списка, и теперь я хочу обновить его, я хочучтобы можно было сохранить все в текстовом файле, но я не знаю, как мне это сделать.

import os
import sys
import time

print("A List")
f = 0
name1 = 0
line = 0
# The Base List
Alist = []

# Prints the list enumerated
def show():
    for i, item in enumerate(Alist, 1):
        print(sep='\n')
        i = str(i)
        print(f"{i}.{item}" + '\n')

Часть файла

В этой части кода я пытался выбратьвторая строка txt-файла, если он существует, но я не знаю, как мне это сделать.

# File
def openF():
    # Reads the txt file
    try:
        global f
        global name1
        global line
        f = open("list.txt", "r")
        line = f.readlines()
        Alist.append(line[0].replace("[", "").replace("]", "").replace("'", "").replace(",", ""))
        print('Reading The list.txt file')
        # Title
        print('Searching for a second line in the file')
        if not line[1] == 0:
            name1 = line[1].replace("[", "").replace("]", "").replace("'", "").replace(",", "")

        if line[1] == 0:
            print('Did not find second line')
            name = input('\n List Title/Name: ')
            name1 = sep = '\n' + '       ' + name
        show()

    # Creates the file if it was not one before
    except:
        f = open('list.txt', "w+")
        print('Creating a new txt file')

openF()

Остальная часть кода

# Saves the list in the txt file
def save(sFile):
    f = open('list.txt', 'w')
    Sfile = str(sFile)
    f.write(Sfile)
    f.close()


# Main loop
while True:
    select = str(input("\nSelect: "))

    # Adding
    if select == "add" or select == "Add" or select == "list":
        add = str(input("\nList: ")) + time.strftime("       %T", time.localtime())
        Alist.append(add)
        print(name1)
        show()
        save(Alist)

    # Deleting
    elif select == "del" or select == "delete" or select == "remove":
        Alist.pop()
        print(name1)
        show()
        save(Alist)

    elif select == "clear" or select == "clean":
        print(100 * "\n")
        print("A List")

    elif select == "delete_list" or select == "del_list":
        f.close()
        os.remove('list.txt')
        os.execl(sys.executable, sys.executable, *sys.argv)

    elif select == "remove1" or select == "del1" or select == "delete1":
        del Alist[0]
        print(name1)
        show()
        save(Alist)
    # Commands
    else:
        print("\n" + "The commands are:\n-To add item (add,list)\n-To delete the entire list(del_list, delete_list)\n-To delete the last item(del,delete,remove)\n-To delete the first item(del1, delete1, remove1)\n-To clear log(clear,clean)" + "\n")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...