I’m attempting to learn a few languages and as such I am doing the same problem on different languages. Here is my code:
def read_one_file():
with open('C:\Python27\inventory.dat', 'r') as f:
invid = f.readline().strip()
invtype = f.readline().strip()
price = f.readline().strip()
stock = f.readline().strip()
title = f.readline().strip()
author = f.readline().strip()
published = f.readline().strip()
return invid, invtype, price, stock, title, author, published
def write_one_file(holdId, holdType, holdPrice, holdStock, holdTitle, holdAuthor, holdPublished):
with open('C:\Python27\inventory.dat', 'w') as f:
invid = holdId
price = holdPrice
newstock = holdStock
published = holdPublished
f.write("Item Id: %s\n" %invid)
f.write("Item Type: %s\n" %holdType)
f.write("Item Price: %s\n" %price)
f.write("Number In Stock: %s\n" %newstock)
f.write("Title: %s\n" %holdTitle)
f.write("Author: %s\n" %holdAuthor)
f.write("Published: %s\n" %holdPublished)
return
invid, invtype, price, stock, title, author, published = read_one_file()
print "Update Number In Stock"
print "----------------------"
print "Item ID: ", invid
print "Item Type: ", invtype
print "Price: ", price
print "Number In Stock: ", stock
print "Title: ", title
print "Author/Artist: ", author
print "Published: ", published
print "----------------------"
print "Please Enter New Stock Number: "
newstock = raw_input(">")
write_one_file(invid, invtype, price, newstock, title, author, published)
EDIT: I’ve tried using str() to convert but still doesn’t run.
EDIT2: I ended up changing %d to %s and seems to work. The only issue is when I run it, it tends to put book on line with 123456.
What ends up happening in the console
Update Number In Stock
----------------------
Item ID: 123456book
Item Type: 69.99
Price: 20
Number In Stock:
Title: Walter_Savitch
Author/Artist: 2011
Published:
----------------------
Please Enter New Stock Number:
>
this is the .txt file:
123456book
69.99
20
Walter_Savitch
2011
something with a newline?
f.write()expects a string as an argument. You’re defininginvid,invtype, etc as tuples, which are not automatically converted to strings. You can either explicitly convert them, using thestr()function, or more likely what you’d like is to use some string formatting, e.g.:where “%d” indicates that nrStock is an integer.
You’ll note that I’ve renamed your
dvariable tonrStock. It’s typically good practice to use descriptive variable names, or an even better idea might be to use a dictionary.