Python Forum

Full Version: Helps with reading csv file - 3 methods
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Everyone,
I try 3 different ways to read csv data and only 1 works.
Can you please help to fix the not working code?
Thank you so much.
HHC

#Working
import pandas as pd
df1 = pd.read_csv (r'C:\temp\text.csv')
print(df1)

#Not working
with open("C:\temp\text.csv", "r") as text:
    print(text)

#Not working
f = open("C:\temp\text.csv", "r")
print(f.read())
What does "not working" mean? What do you expect it to do? What does it do instead? Do you get error messages? What is the output?

The second two should just show you the content of file.
One additional note to add to bowlofred's list.
Please include a small sample of the CSV data.
Hi,
The text.csv has 2 columns:
id info
1, From: abc to xyz
2, From abc yxz

I want to print the data out.

The second code error is:
with open("C:\temp\text.csv", "r") as text:
OSError: [Errno 22] Invalid argument: 'C:\temp\text.csv'

The third code error is:
f = open("C:\temp\text.csv", "r")
OSError: [Errno 22] Invalid argument: 'C:\temp\text.csv'
note the escape sequence \t in the file name. use raw string like in the first snippet, escape the back-slash, e.g. \\ or use forward slash.

Also, in the second snippet you want to print(text.read()). Instead you can iterate over file and print line by line