Kajice
Kajice

Reputation: 712

Python: read csv file (no library)

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?

Upvotes: 0

Views: 98

Answers (1)

fossegrim
fossegrim

Reputation: 301

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

Upvotes: 2

Related Questions