Normally, you would read the CSV file in a row at a time, and carry out any required processing (e.g. converting to ints
or floats
). It is though possible to read all of your rows as a list of rows, with each row holding a list of the values:
import csv
filename = r"C:\Users\prate\Downloads\meal_count_avg_meal.csv"
with open(filename, "rb") as file_my:
csv_my = csv.reader(file_my)
# next(csv_my) # Optionally skip the header
rows = list(csv_my)
As you are still using Python 2.x, you will need to open your file with rb
, which is required for the csv.reader()
object. This approach should give you the same result on Windows or Linux.
rows
would be something like:
[["header1", "header2", "header3"], ["value1", "value2", "value3"]]
This assumes your CSV file is a standard commas separated variable format. If your CSV file contains a header, and you don't want that included in rows
, then simply add the following:
next(csv_my)
Using .readlines()
will keep the line endings (which are different on Windows and Linux).
If one of your environments is Python 3.x, it would need to changed as follows:
import csv
filename = r"C:\Users\prate\Downloads\meal_count_avg_meal.csv"
with open(filename, "r", newline="") as file_my:
csv_my = csv.reader(file_my)
# next(csv_my) # Optionally skip the header
rows = list(csv_my)
If you plan on running the same code on 2.x and 3.x unchanged, your code would have to test which version you are running on and open the file differently depending on the version.