我正在尝试学习几种语言,因此我在不同的语言上做同样的问题。这是我的代码:
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)
。
编辑2:我最后把%d改成了%s,似乎很管用。。
最后在控制台里发生了什么
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:
>
这是.txt文件:
123456本
六十九点九九
二十
沃尔特·萨维奇
二千零一十一
有新线吗?
最佳答案
。您将f.write()
、invid
等定义为tuples,它们不会自动转换为字符串。You can either explicitly convert them, using the invtype
function, or more likely what you'd like is to use some string formatting, e.g.:
"Number in stock%d"%nrStock
其中,“%d”表示nrStock是一个整数。
。。
关于python - python新手,写入功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9204694/