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

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)

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值