Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading