简体   繁体   English

在python中将csv文件读取为字符串

[英]read csv file as a string in python

I accidentally corrupted a csv file (delimiters no longer working - thanks Microsoft Excel!). 我不小心损坏了一个csv文件(分隔符不再起作用-感谢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. 我想通过将其读取为字符串并进行搜索来挽救一些数据-我可以通过在记事本上打开文件来查看文本,但是我不知道如何从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. 但我无法使其正常运行,或者无法在SO / google上找到解决方案。

它应该与以下代码一起使用,但这不是处理csv的最佳方法。

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

Something like: 就像是:

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

You can read csv from this . 您可以从this读取csv。

import csv

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM