如何在python中将文本文件作为参数传递给函数



这是代码,我想看看我做错了什么。我是python函数和链接外部文件的新手,所以如果你能解释一下你的代码,那就太好了。

def get_data(filename):
records = []

with open(filename) as readfile:
lines = readfile.readlines()
for line in lines:
# variable line contains: 
str_rec = line.split(",") 
pname = str_rec[0]
price = int(str_rec[1])
quantity = int(str_rec[2])
records.append([pname, price, quantity])
#caution: indentation
return records

hell= get_data(data.txt)
print(hell)

data.txt是指向另一个文件的链接,我试图将其作为参数传递。

open(filename)接受文件名作为字符串,因此您应该将名称作为字符串传递,而不是实际的文件。

hell= get_data("data.txt")

最新更新