1

I want to read the input.txt line by line and send that as a request to the server and later save the response respectively. how to read and write the data line by line ? my code below works for just one input within input.txt (ex : I am Hungry). Can you please help me how to do it for multiple input ? I did as below. now throwing an error as : File "tts.py", line 198, in TEXT_TO_READ["tts_input"] = line TypeError: 'str' object does not support item assignment

my code :

TEXT_TO_READ = """{

    "tts_type": "text",

    "tts_input": "DUMMY"

}"""
TEXT_TO_READ = json.loads(TEXT_TO_READ)
scriptPath = os.path.abspath(__file__)
scriptPath = os.path.dirname(scriptPath)
fileInput = os.path.join(scriptPath, "input.txt")
try:
    content = open(fileInput, "r")
except IOError:
    print "error message"
    Error_Status = 1
    sys.exit(Error_Status)
for line in content.readlines():
    if len(line):
        TEXT_TO_READ["tts_input"]=line.strip('\n')
        TEXT_TO_READ = json.dumps(TEXT_TO_READ)
        print TEXT_TO_READ

request = Request()
2
  • Please don't vandalise your question. Commented Feb 3, 2016 at 14:50
  • sorry. can you tell me how to fix it ? Commented Feb 3, 2016 at 14:51

1 Answer 1

0

You replaced TEXT_TO_READ with a JSON string:

TEXT_TO_READ = json.dumps(TEXT_TO_READ)

The next iteration you no longer have a dictionary, but a string, so your assignment fails:

TEXT_TO_READ["tts_input"]=line.strip('\n')

Don't use the same variable for both encoded JSON data and a dictionary.

Sign up to request clarification or add additional context in comments.

5 Comments

what should i modify here ?
@sam: what are you trying to achieve? You could just do print json.dumps(TEXT_TO_READ) if all you want to do is write the JSON encoding to stdout. That avoids setting TEXT_TO_READ altogether.
after reading first line from the input.txt then sending a request to the server later again reading the second line and sending the request. but the input here is tts_input. to access tts_input, we are using json loads
You are only using json.loads() to load a hard-coded string at the start of your script. You are not using it on the file contents, if that was the goal.
No, not really. I can only tell you why you got the error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.