dinonuggie
dinonuggie

Reputation: 45

How to pass a text file as an argument to a function in python

Here is the code and I am trying to see what I have done wrong. I am new to python functions and linking external files so it would be nice if you could explain your code.

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 is a link to another file that I am trying to pass as an argument.

Upvotes: 0

Views: 1755

Answers (1)

MrWorldWide
MrWorldWide

Reputation: 498

open(filename) takes the filename as a string, so you should pass the name as a string, not the actual file.

hell= get_data("data.txt")

Upvotes: 2

Related Questions