如何在python中逐行读取和写入.txt文件? [英] How to read and write the .txt file line by line in python?

查看:834
本文介绍了如何在python中逐行读取和写入.txt文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

input.txt-

input.txt -

I am Hungry
call the shopping mall
connected drive

我想逐行读取input.txt并将其作为请求发送到服务器,然后分别保存响应.如何逐行读取和写入数据?

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 ?

以下我的代码仅适用于input.txt中的一个输入(例如:我很饿).您能帮我如何进行多次输入吗?

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 ?

请求:

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()

响应:

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)

推荐答案

为简单起见,让我们对应该发生的事情进行广泛的描述:"我想逐行阅读input.txt并将其作为向服务器的请求,然后分别保存响应. '':

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()

从我的问题中可以得出的结论来看,您已经基本具有功能sendAsRequest(line)saveResponse()(也许使用其他名称),但是您错过了功能readLineByLine('input.txt').在这里:

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.

这篇关于如何在python中逐行读取和写入.txt文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆