Why can't I read csv file in PyCharm?

Viewed 4767

I read some other threads here at stack and one of them is that you don't need to install csv, but when I import csv module, "from cvs import *" is grey coloured.

When you import it in your code it should go gray until used, that's how PyCharm distinguishes between used and unused modules by default.

So how can I solve this?

from csv import *

excel_file = open(”dataset_Facebook.csv”, r)

excel_file.close()

This is traceback I get:

/Users/Melina/Deskop/mmmmm/venv/bin/python /Users/Melina/Deskop/mmmmm/test.py
  File "/Users/Melina/Deskop/mmmmm/test.py", line 3
    excel_file = open(”dataset_Facebook.csv”, r)
                                      ^
SyntaxError: invalid character in identifier

Process finished with exit code 1

And in my terminal

Last login: Mon Jan 14 11:54:57 on ttys000
melinas-MacBook-Pro:~ Melina$ pip install python-csv
Collecting csv
  Could not find a version that satisfies the requirement csv (from versions: )
No matching distribution found for csv
melinas-MacBook-Pro:~ Melina$ 

I Successfully installed argparse-1.4.0 demjson-2.2.4 jtutils-0.0.6 leven-1.0.4 python-csv-0.0.11 xmltodict-0.11.0

1 Answers

You need to fix mistakes in your code.

First, don't import everything in your script. There are other ways to import, but you can use import csv.

Also, strings should be in " " or in ' ', not in ” ”.

And lastly, mode should be string 'r', not just r because then it represent variable.

I won't go into details about using csv module, there is a great article at real python but here is basic example:

import csv

with open('employee_birthday.txt') as csv_file:  # mode is by default 'r' for read.
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')

Cheers !

Related