繁体   English   中英

如何在python中逐行读取和写入.txt文件?

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

input.txt-

I am Hungry
call the shopping mall
connected drive

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

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

要求:

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并将其作为请求发送到服务器,然后分别保存响应。 '':

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

从我可以从您的问题中收集的信息来看,您已经基本上已经具有sendAsRequest(line)saveResponse()函数(可能使用其他名称),但是您错过了函数readLineByLine('input.txt') 这里是:

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.

基本上,您可以简单地:

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

输出将是:

我饿了

打电话给购物中心

连接的驱动器

现在,有关“ with”语句的说明,您可以在这里阅读: http : //effbot.org/zone/python-with-statement.htm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM