如果您不理解,请尝试复制此代码以帮助我,我是python的新手,所以我从以下项目开始:列表制作者,现在我想对其进行更新,我希望它能够保存所有内容一个txt文件,但我不知道该怎么办。
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")