Python Forum
Helps with reading csv file - 3 methods - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Helps with reading csv file - 3 methods (/thread-33643.html)



Helps with reading csv file - 3 methods - hhchenfx - May-13-2021

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())



RE: Helps with reading csv file - 3 methods - bowlofred - May-13-2021

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.


RE: Helps with reading csv file - 3 methods - Larz60+ - May-13-2021

One additional note to add to bowlofred's list.
Please include a small sample of the CSV data.


RE: Helps with reading csv file - 3 methods - hhchenfx - May-13-2021

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'


RE: Helps with reading csv file - 3 methods - buran - May-13-2021

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