PYTHON: How can I add +1 to a number in a file (txt.) -
okay so, i'm trying make little nifty auction program (for habbo if you've played it, that's irrelevant.) essentially, have gotten pretty far it, main goal able view items (including ids easy access) , create new items if want. viewing items works fine, yet i'm struggling second goal, adding items.
i've used bunch of different methods i've found on internet, none seem give desired effect. want have specific text document ("id.txt") starts @ "0" , each time program add item, adds 1 number in file, can call on , give brand new id. far each attempt have has done things add [1] answer, instead of adding 1 itself.
import sys import time def choice1(): print("#####################################################") print("auction log opening") dotdot = "..." char in dotdot: sys.stdout.write(char) time.sleep(0.5) print("") print("1 - choose item id") print("2 - add item") print("3 - return start") choices = input("please make choice. ") if choices == "1" , "#1" , "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" , "#2" , "two": ## itemname = input("what's 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 auction log.") print("2 - open copy/paste log.") print("3 - exit program") onetwothree = input("please make choice. ") if onetwothree == "1" , "one" , "#1" , "one": choice1()
open file , read contents:
with open(filepath) idfile: idstring = idfile.read()
convert string int:
idnumber = int(idstring)
increase number:
idnumber += 1
and write number:
with open(filepath, 'w') idfile: idfile.write('%d' % idnumber)
that's it.
Comments
Post a Comment