我一直在网上搜索一段时间,似乎找不到任何东西.我基本上学习了几种语言,我只是想用不同的语言重新创建一个程序.
def read_one_file():
f = open('C:\Python27\inventory.dat', 'r')
invid = f.readline()
stock = f.readline()
published = f.readline()
price = f.readline()
invtype = f.readline()
title = f.readline()
author = f.readline()
return invid, stock, published, price, invtype, title, author
read_one_file()
print "Update Number In Stock"
print "----------------------"
print "Item ID: ", invid
Run Code Online (Sandbox Code Playgroud)
基本上我是在尝试读取文件,将数据吸收到变量中然后将这些变量传递给main(类?).当我归还它们时,它们仍然无法打印.当我在read_one_file之外初始化它们时,它们仍然没有返回正确的东西.
您需要在某处存储read_one_file()的结果.你在return语句中真正做的是创建一个结果元组.然后,在调用read_one_file时必须解压缩该元组.这是一个例子:
(invid, stock, published, price, invtype, title, author) = read_one_file()
print "Item ID:", invid
Run Code Online (Sandbox Code Playgroud)
这种语法正在执行一种称为"模式匹配"的东西,它所做的就是分解read_one_file返回的元组,并为其中的每个元素赋予名称.我在这里添加了括号,以便更清楚read_one_file返回一个元组,但你可以像这样轻松地写它:
invid, stock, published, price, invtype, title, author = read_one_file()
Run Code Online (Sandbox Code Playgroud)
这一切都很好,但实际上,这是一种从函数中返回东西的坏方法.如果你想从这样的函数返回很多变量,那么dict可能是一种更好的方法.此外,您可能希望使用with语句来确保在完成文件后关闭并正确清理文件.以下是使用该策略的代码:
def read_one_file():
with open('C:\Python27\inventory.dat', 'r') as f:
return dict(invid = f.readline().strip(),
stock = f.readline().strip(),
published = f.readline().strip(),
price = f.readline().strip(),
invtype = f.readline().strip(),
title = f.readline().strip(),
author = f.readline().strip())
results = read_one_file()
print "Update Number In Stock"
print "----------------------"
print "Item ID: ", results['invid']
Run Code Online (Sandbox Code Playgroud)
编辑:我更改了上面的代码以使用.strip(),因为(正如@NiklasB.所指出的),新行仍然包含在readline中.
对于您似乎正在尝试做的事情,这更清晰一些。注意我假设您的inventory.dat文件不是很大,并且至少有 7 行。
def read_one_file(fname=r'C:\Python27\inventory.dat'):
with open(fname) as f:
lines = [line.strip() for line in f]
keys = ['invid', 'stock', 'published', 'price', 'invtype', 'title', 'author']
inventory_item = dict(zip(keys, lines[:len(keys)]))
return inventory_item
d = read_one_file()
print("Update Number In Stock")
print("----------------------")
print("Item ID: ", d['invid'])
Run Code Online (Sandbox Code Playgroud)
对原始代码的更改细分:
fname 作为默认参数传递,而不是硬编码到函数中fnamer'raw string'带有r前缀的字符串,这将防止反斜杠转义被错误处理(例如,如果您的文件名是 图像,如果您使用的是普通字符串,则在 Windows 中将ninventory.dat其\作为路径分隔符,您将在文件名中得到一个换行符)with声明。[line.strip() for line in f]是一个列表推导式,用于从数据中删除尾随换行符并将这些行存储在名为lines.n使用 python 将文件的第一行映射为键的值dict。lines[:len(keys)]将列表切片到前 n 项,其中n是上面声明的键数。zip只需将 2 个可迭代对象(在本例中为键和文件中的值)配对成一个可迭代的元组,这是创建新的dict.d = read_one_file()将文件读取的结果存储到变量中。在您的代码中,这丢失了,因为没有引用所持有的函数的返回值。d['invid']访问'invid'存储在 dict中的键的值d。您应该类似地访问其他值。