Python CSV file issue

ukerandi
ukerandi used Ask the Experts™
on
Hi,
I have written following Python code,But it's Not working. No results showing

with open('Test.csv') as csvfile:
	      readCSV=csv.reader(csvfile,delimiter=',')
	      print(readCSV)
	      for row in readCSV:
		      print(row)

Open in new window

Program executes on the Python 3.7.0 Shell
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
nociSoftware Engineer
Distinguished Expert 2018

Commented:
Try saving this as: csv-test.py

import csv
with open('Test.csv') as csvfile:
      readCSV=csv.reader(csvfile, delimiter=',')
      print(readCSV)
      for row in readCSV:
            print(row)

Open in new window


(basicly the import was missing to actualy load the csv object.)
There are several things to be improved and one (possibly two) bugs. As noci wrote, you should use import csv to work with the module.

The bug may not manifest for your data, but the open command is missing the argument newline='' (see https://docs.python.org/3/library/csv.html#csv.reader). This is important as the reader have to interpret newlines on its own. The reason is that the newline can be wrapped as the value of the element.

The second possible bug is that you mix tabs and spaces for indentation. The style guide correctly suggests that you shoul always use 4 spaces for one indentation level. The editors can be set so.

import csv

fname = 'Test.csv'
with open(fname, newline='') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        print(row)

Open in new window


The following are suggestions based on my experience:

1. Whenever you use explicitly named file, you should use fname like variable to store it first. Only then you use the variable. The reason is that it is likely the file name will be used later again, and you do not want to type the explicit name again because of possible typo mistake. The other reason is that you may want to convert the part of the code to the function, and the fname just becomes the parameter (less work in future).

2. If there is no specific reason for another name, use (by your own convention) the name reader  for the csv.reader object. There were thinking hard to pick the name in the module -- even though it may not look so. Keeping the reader name in your code, it will be more readable for others... and for you in future.

3. Keep your own convention for naming temporary objects using the same identifiers (short, simple, general name) -- like f for the file object if you do not need anything more special.

4. Put one space around the = (assignment), unless it is part of the named argument (like in the newline='' -- then it is without spaces).

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial