Trying to create a csv using python, and getting “list indices” error

Tags: python csv
By : glongo
Source: Stackoverflow.com
Question!

In my last question, I asked how to get python to assign a set of values to phrases in a csv files. I was told to create a list of tuples, and this worked great.

Currently my list, called clean_titles looks like this:

[('a', 1),
 ('a', 1),
 ('a', 1),
 ('a', 1),
 ('a', 1),
 ('a', 1),
 ('a', 1),
 ('a', 1),
 ('b', 2),
 ('b', 2),
 ('b', 2),
 ('b', 2),
 ('b', 2),
 ('b', 2),
 ('c', 3),
 ('c', 3),
 ('c', 3),
 ('c', 3),
 ('c', 3)]

Now I want to take the list, and export it to as CSV file. I want the name of the phrases in one column and the assigned number in another column.

with open("fiancee_wordfreq.csv" , "wb") as f:
     writer = csv.writer(f)  
  for val in clean_titles:
     writer.writerow([val])

But I keep getting an error message that "list indices must be integers not unicode"

What am I doing wrong or what am I missing. Thanks for your help.

By : glongo


Answers

(My answer is for Python3)

You are opening the file in "bytes" mode. It worked for me when I removed the "b" argument:

with open("testabc.csv" , "w") as f:
  writer = csv.writer(f)  
  for val in clean_titles:
     writer.writerow(val)

Also, you can just use a built-in writerows function to be less verbose:

with open("testabc.csv" , "w") as f:
  writer = csv.writer(f)  
  writer.writerows(clean_titles)
By : brianpck


Using vanilla JS :

From the MDN doc :

function reqListener () {
  console.log(this.responseText);
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Read the doc and ndcomix SO link to go further (error checking and such)



Just use jquery. It's easy fun and extensible. Don't try bizzare uses. Be sure all the time to be compatible through all the browser. If you copy this and run it under a local or remote webserver will work like a charm. Cheers.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.ajax({url: "test.txt", success: function(result){
            $("#div1").html(result);
        }});
    });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>


This video can help you solving your question :)
By: admin