简体   繁体   English

readlines() 在用于 CSV 文件时不起作用

[英]readlines() not working when used on a CSV file

So have a "file.csv" and I want to extract some data from it using Python.所以有一个“file.csv”,我想使用 Python 从中提取一些数据。
The problem for me is that the lines are formatted not in standard csv format, but instead a line looks like this:我的问题是这些行的格式不是标准的 csv 格式,而是一行看起来像这样:

;a_value=value;b_value=value;

So my idea was to use .replace() to edit everything in a line so that in the end it looks as wished:所以我的想法是使用.replace()来编辑一行中的所有内容,以便最终看起来如愿:

'a_value':'value', 'b_value':'value'  

In order to iterate and modify every line I followed the idea from this question from Modify csv files?为了迭代和修改每一行,我遵循了来自Modify csv files? 的这个问题的想法

But I get:但我得到:

AttributeError: 'str' object has no attribute 'readline'

My code:我的代码:

with open(name_file, "r") as csv_file:
   data=name_file.readlines()
csv_file=close()

csv_file=open(name_file, "w")
for row in csv_file:
    #Replace commands
f.close()

It's something pretty simple in this case;在这种情况下,这很简单; When you open a file using with open , you need to operate on the file type variable you defined rather than using the path of the file.当您使用with open打开文件with open ,您需要对您定义的文件类型变量进行操作,而不是使用文件的路径。

In this case, you open the file but then try to read the string based path of the file, rather than the file type.在这种情况下,您打开文件,然后尝试读取基于字符串的文件路径,而不是file类型。

So you'd need to rewrite your code as such:所以你需要重写你的代码:

with open(name_file, "r") as csv_file:
   data=csv_file.readlines()

Hope this helped!希望这有帮助!

PS, the close method is only needed when you don't use the with keyword, when you exit the indented block, the file is closed. PS,close方法只有在不使用with关键字时才需要,当退出缩进块时,文件被关闭。

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

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