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

Time:06-08

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.

CodePudding user response:

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")
  • Related