-1

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()
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    `data = csv_file.readlines()` is probably what you want. At the moment, you're trying to do `readlines()` on `name_file` which probably is a string. And I'm not sure what `close()` should return? Did you mean to do `csv_file.close()`? If that's the case, you don't need it because the `with ...` context closes the file for you when you exit that indent block - that one of the major key points of the whole context. – Torxed Jan 21 '19 at 18:43
  • As Torxed said you need to read the variable which is created by your opening the file, a.k.a. `csv_file` because what you are currently doing is trying to run `readlines()` on the string which is the name of your file not on the variable you have just created with the open function – 13ros27 Jan 21 '19 at 18:46

1 Answers1

1

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!

P.S, the close method is only needed when you don't use the with keyword, when you exit the indented block, the file is closed.

Aditya Diwakar
  • 180
  • 1
  • 9