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

青春壹個敷衍的年華 提交于 2019-12-13 05:38:09

问题


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)

回答1:


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.



回答2:


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



来源:https://stackoverflow.com/questions/35175730/how-to-read-and-write-the-txt-file-line-by-line-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!