简体   繁体   中英

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.
The problem for me is that the lines are formatted not in standard csv format, but instead a line looks like this:

;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:

'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?

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.

In this case, you open the file but then try to read the string based path of the file, rather than the file type.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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