好吧,我正在尝试制作这个漂亮的小拍卖程序(如果你玩过的话,这是哈宝的拍卖程序,但这无关紧要。)本质上,我已经取得了很大的进展,但我的主要目标是能够查看项目(包括其 ID,以便于访问)并根据需要创建新项目。 目前查看项目效果很好,但我正在努力实现第二个目标,即添加项目。
我使用了在互联网上找到的许多不同的方法,但似乎没有一个真正能达到预期的效果。我想要一个特定的文本文档(“ID.txt”),它只是从“0”开始,然后每次我的程序要添加一个项目时,它都会在文件中的该数字上添加 1,以便我可以调用并提供一个全新的 ID。到目前为止,我的每次尝试都完成了诸如在答案中添加 [1] 之类的操作,而不是添加 1 本身。
import sys
import time
def choice1():
print("#####################################################")
print("Auction log opening")
dotDot = "..."
for char in dotDot:
sys.stdout.write(char)
time.sleep(0.5)
print("")
print("1 - Choose an item ID")
print("2 - Add an item")
print("3 - Return to start")
choices = input("Please make your choice. ")
if choices == "1" and "#1" and "one":
itemID = input("Enter item ID: ")
if itemID == "#0001":
aLog = open("auctionlist.txt")
lines = aLog.readlines()
print("#####################################################")
print("")
print(lines[0])
print(lines[1])
print(lines[2])
print(lines[3])
print("")
print("#####################################################")
elif itemID == "#0002":
aLog = open("auctionlist.txt")
lines = aLog.readlines()
print("#####################################################")
print("")
print(lines[4])
print(lines[5])
print(lines[6])
print(lines[7])
print("")
print("#####################################################")
elif choices == "2" and "#2" and "two":
## itemName = input("What's the item's name? ")
## itemBought = input("Item buy price? ")
## itemAvg = input("Item average? ")
## itemSell = input("Target sell price? ")
ID = open("ID.txt", "r+")
content = ID.readlines()
content[0] = content[0]+"1"
ID.write(str(content))
ID.close()
print("#####################################################")
print("Title: Auction House v0.1")
print("Author: Alasdair Cowie")
print("Date: 08/07/15")
print("#####################################################")
print("1 - Open the auction log.")
print("2 - Open the copy/paste log.")
print("3 - Exit the program")
oneTwoThree = input("Please make your choice. ")
if oneTwoThree == "1" and "one" and "#1" and "One":
choice1()
最佳答案
打开文件并读取其内容:
with open(filePath) as idFile:
idString = idFile.read()
将字符串转换为 int:
idNumber = int(idString)
增加数量:
idNumber += 1
并写回该数字:
with open(filePath, 'w') as idFile:
idFile.write('%d' % idNumber)
就是这样。
关于PYTHON:如何将+1添加到文件(txt)中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31304241/