正在获取.py文件以将列表保存到.txt文件而不覆盖它



[初学者尝试学习蟒蛇3,请像我5一样解释]

所以我写了这个代码:

x = [2, 3, 4, 5] # The List
print(f"The list is {x}.") # Displays default list
user = int(input("A number to add to list: ")) # Asks user to add a number
x.append(user) # Appends user's number into list
file = open("ListElements.txt", "w")  # Opens a file for writing and puts it in the file variable
file.write(f"{x}") # Writes the entire list + the appended element into new file
file.close()  # Closes the file
print("The List is now: ") # Print out the string
print(open('ListElements.txt', "r").read()) # Prints out the contents of the ListElements.py

它应该取一个数字列表,并要求用户在列表中添加一个数字。然后,它将新列表作为文本保存到ListElements.txt文件中。它做得很好。但是,如果我再次运行该程序,它会覆盖ListElements.txt文件,而不是添加到其内容中。如何将其保存为新行而不覆盖它?

有一个名为append的方法,使用a可以将其添加到文件末尾。请确保该文件首先存在。

x = [2, 3, 4, 5] # The List
print(f"The list is {x}.") # Displays default list
user = int(input("A number to add to list: ")) # Asks user to add a number
x.append(user) # Appends user's number into list
for num in x:
file = open("ListElements.txt", "a")  # Opens a file for writing and puts it in the file variable
file.write(f"{num}n") # Writes the entire list + the appended element into new file
file.close()  # Closes the file
print("The List is now: ") # Print out the string
new_x = []
for line in open('ListElements.txt', "r").readlines():
new_x.append(int(line))
print(new_x) # Prints out the contents of the ListElements.py

确保在你写的每一件事之后都插入一行新行,否则它将像12345而不是

1
2
3
4
5

最新更新