0

My task is to read a CSV file: the function should open the file, read the contents and convert the lines into a list of string tuples. The different tuple indices represent the various attributes of the record.

While not using any library. (Also assuming the input is always valid)

def read_csv(path):
    file = open(path, "r")
    content_list = []

    for line in file.readlines():
        record = tuple(line.split(","))
        content_list.append(record)

    return content_list


print(read_csv("/path/example.csv"))

My example file looks like this:

Age,Gender,Weight (kg),Height (cm)
28,Female,58,168
33,Male,,188

With my example file I get:

[('Age', 'Gender', 'Weight (kg)', 'Height (cm)\n'), ('28', 'Female', '58', '168\n'), ('33', 'Male', '', '188')]

How can I remove the "\n"? I tried different things. For example, replacing "\n" with simply "". That didn't work. Can someone help?

1
  • 6
    Use strip before split. Commented Oct 29, 2019 at 10:35

1 Answer 1

2

You can make a for loop that loops through record and uses the replace method to replace all instances of newline "\n" with an empty string "".

def read_csv(path):
file = open(path, "r")
content_list = []

for line in file.readlines():
    record = line.split(",")
    for i in range(len(record)):
        record[i] = record[i].replace("\n","")

    content_list.append(tuple(record))

return content_list

print(read_csv("/path/example.csv"))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.