sam
sam

Reputation: 203

How to read and write the .txt file line by line in python?

input.txt -

I am Hungry
call the shopping mall
connected drive

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 ?

Request :

fileInput = os.path.join(scriptPath, "input.txt")
if not os.path.exists(fileInput):
    print "error message"
    Error_Status = 1
    sys.exit(Error_Status)
else:
    content = open(fileInput, "r").read()
    if len(content):
        TEXT_TO_READ["tts_input"] =  content
        TEXT_TO_READ = json.dumps(TEXT_TO_READ)
    else:
        print "error message 2"

request = Request()

Response :

res = h.getresponse()
data = """MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=--Nuance_NMSP_vutc5w1XobDdefsYG3wq
""" + res.read()

msg = email.message_from_string(data)

for index, part in enumerate(msg.walk(), start=1):
    content_type = part.get_content_type()
    payload = part.get_payload()

    if content_type == "audio/x-wav" and len(payload):
        with open('Sound_File.pcm'.format(index), 'wb') as f_pcm:
            f_pcm.write(payload)
    elif content_type == "application/json":
        with open('TTS_Response.txt'.format(index), 'w') as f_json:
            f_json.write(payload)

Upvotes: 0

Views: 4064

Answers (2)

DainDwarf
DainDwarf

Reputation: 1669

To keep it stupid simple, let's implement your broad description of what should happen : ''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. '' :

for line in readLineByLine('input.txt'):
    sendAsRequest(line)
    saveResponse()

From what I can gather from your question, you already have basically functions sendAsRequest(line) and saveResponse() (maybe under another name), but you miss the function readLineByLine('input.txt'). Here it is:

def readLineByLine(filename):
    with open(filename, 'r') as f: #Use with statement to correctly close the file when you read all the lines.
        for line in f:    # Use implicit iterator over filehandler to minimize memory used
            yield line.strip('\n') #Use generator, to minimize memory used, removing trailing carriage return as it is not part of the command.

Upvotes: 2

Maxim Dunavicher
Maxim Dunavicher

Reputation: 635

Basically you can simply:

with open('filename') as f:
     for line in f.readlines():
         print line

The output will be:

I am Hungry

call the shopping mall

connected drive

Now for an explanation about the "with" statement you can read here: http://effbot.org/zone/python-with-statement.htm

Upvotes: -1

Related Questions