Jim Eisenberg
Jim Eisenberg

Reputation: 1500

read csv file as a string in python

I accidentally corrupted a csv file (delimiters no longer working - thanks Microsoft Excel!). I want to salvage some data by reading it as a string and searching for things - I can see the text by opening the file on notepad, but I can't figure out how to load that string from the filepath in python.

I imagine it would be a variation of

csv_string = open(filepath, 'something').read()

but I can't get it to work, or find a solution on SO / google.

Upvotes: 0

Views: 72

Answers (3)

alec_djinn
alec_djinn

Reputation: 10819

It should work with the following code, but it is not the best way to deal with csv.

csv_string = ''.join(open(filepath, 'r').readlines())

Upvotes: 1

Yash Shukla
Yash Shukla

Reputation: 141

You can read csv from this .

import csv

reader = csv.reader(open("samples/sample.csv"))    
for title, year, director in reader:
   print year, title

Upvotes: 0

brunns
brunns

Reputation: 2764

Something like:

with open(filepath, 'r') as corrupted_file:
    for line in corrupted_file:
        print(line) # Or whatever

Upvotes: 0

Related Questions