2016-02-03 34 views
0

input.txt中 -如何在python中逐行讀寫.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) 
+0

你能告訴我怎麼做? – sam

回答

-1

基本上就可以簡單地說:

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

輸出將是:

我餓了

呼叫商場

連接的驅動

現在關於「同向」的解釋語句,您可以在這裏閱讀: http://effbot.org/zone/python-with-statement.htm

+1

使用'readlines()'效率低下,可能會產生內存錯誤。只需遍歷該文件:https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects –

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. 
+0

fileInput作爲input.txt根據我的代碼,但如何採用你的答案在我的代碼? – sam

+0

你能告訴我怎麼樣? – sam

+0

你有問題隔離你的代碼的部分,並重構它們的功能?或者,您是否有編寫使用'def functionName(args)'語法的函數的代碼的問題? – DainDwarf