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
  Failing reading a file and cannot exit it... tester_V 8 366 Aug-19-2022, 10:27 PM
Last Post: tester_V
  Reading .csv file doug2019 4 590 Apr-29-2022, 09:55 PM
Last Post: deanhystad
Question Pandas : How to create an algorithm that helps me improve results and creating new co Smordy 8 918 Apr-10-2022, 10:28 PM
Last Post: Larz60+
  Reading an Input File DaveG 1 478 Mar-27-2022, 02:08 AM
Last Post: deanhystad
  Initializing, reading and updating a large JSON file medatib531 0 683 Mar-10-2022, 07:58 PM
Last Post: medatib531
  Reading Excel file and use a wildcard in file name and sheet name randolphoralph 6 1,842 Jan-13-2022, 10:20 PM
Last Post: randolphoralph
  Loop reading csv file problem faustineaiden 1 827 Dec-11-2021, 08:40 AM
Last Post: ibreeden
Question In need of insight regarding Python file reading mechanisms. EnfantNicolas 7 1,709 Sep-18-2021, 10:39 AM
Last Post: ndc85430
  Help with reading json file hhchenfx 5 2,722 Jul-07-2021, 01:58 PM
Last Post: hhchenfx
  [Solved] Reading every nth line into a column from txt file Laplace12 7 3,083 Jun-29-2021, 09:17 AM
Last Post: Laplace12

Forum Jump:

User Panel Messages

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