Python Forum
Helps with reading csv file - 3 methods
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Helps with reading csv file - 3 methods
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.

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

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

#Not working
f = open("C:\temp\text.csv", "r")
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.
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( Instead you can iterate over file and print line by line
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs


Possibly Related Threads…
Thread Author Replies Views Last Post
Question In need of insight regarding Python file reading mechanisms. EnfantNicolas 7 237 Sep-18-2021, 10:39 AM
Last Post: ndc85430
  Help with reading json file hhchenfx 5 622 Jul-07-2021, 01:58 PM
Last Post: hhchenfx
  [Solved] Reading every nth line into a column from txt file Laplace12 7 784 Jun-29-2021, 09:17 AM
Last Post: Laplace12
  help with project of reading and searching big log file korenron 6 408 Jun-24-2021, 01:57 PM
Last Post: korenron
  Subprocess.Popen() not working when reading file path from csv file herwin 13 1,734 May-07-2021, 03:26 PM
Last Post: herwin
  find the header location in a .bin file without reading the whole file at a time SANJIB 0 576 Mar-05-2021, 04:08 PM
Last Post: SANJIB
  Reading a csv file Led_Zeppelin 2 799 Feb-26-2021, 05:48 AM
Last Post: buran
  reading a csv file Led_Zeppelin 3 994 Feb-19-2021, 02:16 PM
Last Post: Led_Zeppelin
  Code not reading http link from .txt file (Beginner level) plarrip 3 703 Dec-17-2020, 11:33 PM
Last Post: bowlofred
  Reading from a file. krhoades 3 753 Dec-03-2020, 09:52 PM
Last Post: krhoades

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020