我正在尝试学习几种语言,因此我在不同语言上也会遇到同样的问题.这是我的代码:
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)
Run Code Online (Sandbox Code Playgroud)
编辑:我已经尝试使用str()转换但仍然没有运行.EDIT2:我最终将%d更改为%s并且似乎有效.唯一的问题是当我运行它时,它倾向于将书放在123456上.
最终在控制台中发生了什么
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:
>
Run Code Online (Sandbox Code Playgroud)
这是.txt文件:
123456book 69.99 20
Walter_Savitch 2011
换行的东西?
f.write()期望一个字符串作为参数.你定义invid,invtype等的元组,它不会自动转换为字符串.您可以使用该str()函数显式转换它们,或者您更喜欢使用某些字符串格式,例如:
"Number in stock%d"%nrStock
Run Code Online (Sandbox Code Playgroud)
其中"%d"表示nrStock是一个整数.
你会注意到我已经将你的d变量重命名为nrStock.使用描述性变量名称通常是一种好习惯,或者更好的想法可能是使用字典.
| 归档时间: |
|
| 查看次数: |
8254 次 |
| 最近记录: |