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

时间:2016-02-03 11:25:05

标签: python python-2.7 for-loop readline readlines

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)

2 个答案:

答案 0 :(得分:1)

为了简单起见,让我们实现你应该发生什么的广泛描述:''我想逐行读取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.

答案 1 :(得分:-1)

基本上你可以简单地说:

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

输出将是:

我饿了

致电购物中心

连接驱动器

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