2017-07-19 31 views
0

我正在嘗試編寫一個程序來幫助我理解如何讀取和寫入文本文件。我理解它的基本思想,但是當我嘗試將它們放入一個模塊中時,我無法讓它工作並獲得TypeError:期望的str,字節或os.PathLike對象,而不是第63行中列出的printData中的open (a)作爲f:有人能解釋我做錯了什麼嗎?無法顯示在Python列表中加載的文本文件

### Subprogram getData(fn) 
    # This will load the string into a list 

    def getData(fn): 
     # Opens the file and enables read 
     with open(fn, "r") as ins: 
      # Creates the list to load the string 
      list = [] 
      for line in ins: 
       # Appends the string into the list 
       list.append(line) 
     return list 

    # ============================================================================== 

    ### Subprogram printData(a) 
    # Displays the string 

    def printData(a): 
     # Opens the file 
     with open(a) as f: 
      for line in f: 
       # Displays the content of the string 
       print(line, end = "") 

    # ============================================================================== 

    def main(): 
     # Declare text[] and array 
     text = [] 
     # Assigns the fileName to data.txt 
     fileName = "data.txt" 

     # Calls saveDate() and assigns the string 
     saveData(fileName, "This is a test") 
     # Calls getData() 
     textIn = getData(fileName) 
     # Calls printData() 
     printData(textIn) 

    main() 
+0

saveData丟失 – aless80

回答

0

您所呼叫的打開文件的方法,但你的文件名是一個字符串的列表,而不是讓你得到一個錯誤。在你的get數據方法中,你創建了一個字符串列表,也許你打算用這些名字之一打開一個文件。無論哪種方式,文件名不能是一個列表。

+0

@Cary。謝謝。你和Moe a給了我的建議確實幫助我理解我做錯了什麼。 – Mike

+0

很高興聽到它。請投票和/或接受答案:) –

0

您的getData()方法返回list,然後您將它傳遞給printData(),它需要一個文件而不是list。這就是爲什麼你得到TypeError您需要更改printData()以下:

def printData(a): 
    for line in a: 
     # Displays the content of the string 
     print(line, end = "") 
+0

非常感謝。這對我來說更有意義。我只是在學習python,當我感到困惑時,它確實有助於讓某人解釋它。 – Mike

+0

嘿邁克。將來,如果您遇到任何錯誤或者卡住了,請記住「印刷」您所能做的一切。然後你會看到每個變量的輸出和類型。 –

0

printData(a),被認爲是一個列表而不是一個文件,所以從printData刪除with open(a) as f:線或將文件發送函數printData不是返回的列表getData

+0

謝謝。我真的很感激幫助。每個人都幫助我理解我做錯了什麼。 – Mike