I tried to open a csv file in jupyter notebook, but it shows error message. And I didn't understand the error message. CSV file and jupyter notebook file is in the same directory. plz check the screenshot to see the error message
-
4You should place code directly in here, and never share screen shots of code. It makes it very difficult to troubleshoot since people cannot copy paste your code.probat– probat2019-12-08 20:48:12 +00:00Commented Dec 8, 2019 at 20:48
-
1stackoverflow.com/help/minimal-reproducible-example, stackoverflow.com/help/how-to-askprobat– probat2019-12-08 20:48:45 +00:00Commented Dec 8, 2019 at 20:48
-
The problem I suppose is in the CSV file looking at the error. Maybe NAs or bad formatted data. Check your CSV for consistencyEnrico Belvisi– Enrico Belvisi2019-12-08 21:14:40 +00:00Commented Dec 8, 2019 at 21:14
-
I can suggest you anyway to this solution stackoverflow.com/a/58200424/5333248 . If not working try encoding='UTF-8' instead. If both don't work, solution could be much harder to findEnrico Belvisi– Enrico Belvisi2019-12-08 21:28:45 +00:00Commented Dec 8, 2019 at 21:28
3 Answers
As others have written it's a bit difficult to understand what exactly is your problem.
But why don't you try something like:
with open("file.csv", "r") as table:
for row in table:
print(row)
# do something
Or:
import pandas as pd
df = pd.read_csv("file.csv", sep=",")
# shows top 10 rows
df.head(10)
# do something
Comments
You can use the in-built csv package
import csv
with open('my_file.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
print(row)
This will print each row as an array of items representing each cell.
However, using Jupyter notebook you should use Pandas to nicely display the csv as a table.
import pandas as pd
df = pd.read_csv("test.csv")
# Displays top 5 rows
df.head(5)
# Displays whole table
df
Resources
The csv module implements classes to read and write tabular data in CSV format. It allows programmers to say, “write this data in the format preferred by Excel,” or “read data from this file which was generated by Excel,” without knowing the precise details of the CSV format used by Excel.
Read More CSV: https://docs.python.org/3/library/csv.html
pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language.
Read More Pandas: https://pandas.pydata.org/pandas-docs/stable/getting_started/10min.html