2016-11-03 37 views
-1

嘗試在Python中使用\ n時,我遇到了一個反覆出現的問題。我試圖從另一個文本文件中提取數據後,將代碼寫入文本文件當我運行代碼時,它總是在\ n之後顯示「行後續字符出現意外的字符」錯誤。這是我目前使用的代碼。 n「連續字符後出現意外字符」

while True: 
while True: 
    try: 
     Prod_Code = input("enter an 8 digit number or type Done to get your final receipt: ") 
     check = len(Prod_Code) 
     int(Prod_Code) 

     if check == 8: 
      print("This code is valid") 



      with open('Data Base.txt', 'r') as searchfile: 
       for line in searchfile: 
        if Prod_Code in line: 
         print(line) 
         receipt = open('Receipt.txt', 'w') 
         receipt.write(line, \n) 
         receipt.close() 
         break 

     else: 
      print("incorrect length, try again") 

    except ValueError: 
     if Prod_Code == "Done": 
      print("Your receipt is being calculated") 
      exit() 

     else: 
      print("you must enter an integer") 
+1

寫''\ n「'而不是使它成爲+,所以'line +」\ n「' – dendragon

+0

它需要是''\ n'' – roganjosh

回答

2

不像printwrite只接受一個參數(也可以不寫彩車&整數沒有它們轉換爲字符串 - 不是這裏的問題)。

而你的\n char必須被引用當然。所以寫:

receipt.write(line + "\n") 

追隨你的評論,似乎是因爲你寫的只有一條線(無追加)你的代碼不能按預期工作,即使此修復程序後你打破環路只要你匹配1行:2個只寫1行的理由。我建議以下修復:

receipt = None 

with open('Data Base.txt', 'r') as searchfile: 
    for line in searchfile: 
     if Prod_Code in line: 
      print(line) 
      if receipt == None: 
       receipt = open('Receipt.txt', 'w') 
      receipt.write(line+"\n") 

if receipt != None: 
    receipt.close() 

只有在匹配時纔會創建輸出文件。它在循環過程中保持打開狀態,因此附加行。最後,如果需要,它會關閉該文件。

請注意,如果您多次執行此操作,則此類線性搜索不是最佳的。最好將文件的內容存儲在list中,然後在行上進行迭代。但這是另一個故事...

+0

這已經解決了問題然而,程序每次仍然寫入同一行,並且不會啓動新行。有想法該怎麼解決這個嗎? –

+0

@joewalley'receipt = open('Receipt.txt','w')'每次都會以寫入模式打開文件,因此會覆蓋以前的數據並重新開始。 – roganjosh

+0

啊,對,謝謝。一切正常,現在應該如此。 –

相關問題