好吧,我正在尝试制作这个小漂亮的拍卖计划(如果你玩过它,对于habbo,但那是无关紧要的。)基本上,我已经相当远,但我的主要目标是能够查看项目(包括其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()
答案 0 :(得分:1)
打开文件并阅读其内容:
with open(filePath) as idFile:
idString = idFile.read()
将字符串转换为int:
idNumber = int(idString)
增加数量:
idNumber += 1
并写下这个号码:
with open(filePath, 'w') as idFile:
idFile.write('%d' % idNumber)
就是这样。
答案 1 :(得分:0)
您可以使用替换方法,并增加代码, 你会搜索i-1并用i或类似的东西替换它。
print ("Text to search for:i-1")
textToSearch = input( "> " )
print ("Text to replace it with:i")
textToReplace = input( "> " )
print ("File to perform Search-Replace on:")
fileToSearch = input( "> " )
fileToSearch = 'D:\dummy1.txt'
tempFile = open( fileToSearch, 'r+' )
for line in fileinput.input( fileToSearch ):
if textToSearch in line :
print('Match Found')
else:
print('Match Not Found!!')
tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()
input( '\n\n Press Enter to exit...' )