0
from csv import reader
nfl = list(reader(open("nfl.csv")))

or like this:

import csv
f = open("my_data.csv")
csvreader = csv.reader(f)
my_data = list(csvreader)

Does it make much difference if I write a code in a first way? Is it as fast as the second one? How is it written in the real corporate life?

HardRock4Life
  • 177
  • 1
  • 9
  • 4
    It probably doesn't use either method, but the second is probably better. You should be using `with` context manager for handling files since that will ensure that the file gets closed at the end. Also, do you want all of the lines in a single list because it might be desirable to iterate through the reader line by line if you don't necessarily want all of the data? – roganjosh Aug 24 '18 at 09:31
  • The [documentation](https://docs.python.org/3/library/csv.html#examples) gives examples of the correct way of reading CSV files – roganjosh Aug 24 '18 at 09:33
  • 3
    @AkshayNevrekar that's a particularly heavy dependency for reading CSV files if the OP doesn't already have `pandas` for some other purpose – roganjosh Aug 24 '18 at 09:35
  • @roganjosh So, I can iterate if I don't want all the data? But what happens, if the file remains opened? Is there a risk that it might be accidentally edited by someone from aside? Or it just eats PC's memory? – HardRock4Life Aug 24 '18 at 09:43
  • I'm not sure I understand the question. You're talking about concurrent access to a file? – roganjosh Aug 24 '18 at 09:49
  • @roganjosh That's right, is it possible? – HardRock4Life Aug 24 '18 at 09:50
  • 1
    There's an answer [here](https://stackoverflow.com/questions/11853551/python-multiple-users-append-to-the-same-file-at-the-same-time) about concurrency and [here](https://stackoverflow.com/questions/7395542/is-explicitly-closing-files-important) about closing files – roganjosh Aug 24 '18 at 09:58

1 Answers1

2

Neither method is ideal because you want to ensure the file is closed at the end. For this purpose you can use with to ensure the file is closed once you're finished processing it. This avoids mistakes where you might forget to call .close() on the file. More info on context managers can be found here. Examples of this can be seen in the documentation.

So, something like:

with open('my_data.csv') as infile:
    reader = csv.reader(infile)
    data = list(reader)

Note, however, this loads the whole contents of the file into memory. As the documentation examples show, you could instead iterate through the reader object if you don't need the whole file in memory.

roganjosh
  • 12,594
  • 4
  • 29
  • 46