The csv-module is implemented in C. It's even faster (I guess).
But this does not matter. At the end it's nearly the same code.
For example, the use of the method readlines is not good.
What happens if the csv-file is 16 GiB big and you have only 8 GiB memory?
(of course by this size, you can't put the results in a list)
Here the last example:
The fileobject is an Iterator. Iterating over the iterator yields line by line with line ending (\n).
The csv-object is an Iterator. Iterating over the iterator yields row by row, where the row is already splitted into columns.
The rest is just index access and appending to a list.
If you're unsure, what the code does, just print the row to console inside the loop.
But this does not matter. At the end it's nearly the same code.
For example, the use of the method readlines is not good.
What happens if the csv-file is 16 GiB big and you have only 8 GiB memory?
(of course by this size, you can't put the results in a list)
Here the last example:
data = open(csv_file, "r").readlines() for row in data: row_list=row.strip().split(",") # codeModified to consume lesser memory:
data = open(csv_file, "r") for row in data: row_list=row.strip().split(",") # codeNow with a context manager:
with open(csv_file, "r") as data: for row in data: row_list=row.strip().split(",") # codeNow the code with csv.reader:
with open(csv_file, "r") as data: reader = csv.reader(data, delimiter=',') # header = next(reader) # this skips the first line for row in reader: # codeThe difference is, that the csv.reader splits the row for you. It does more, but it's not always needed.
The fileobject is an Iterator. Iterating over the iterator yields line by line with line ending (\n).
The csv-object is an Iterator. Iterating over the iterator yields row by row, where the row is already splitted into columns.
The rest is just index access and appending to a list.
If you're unsure, what the code does, just print the row to console inside the loop.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!