2016-08-16 118 views
-3

我得到一個TypeError: object of type file' has no len() 我已經追溯到執行時建立的路徑的問題。用戶創建的日誌文件

我錯過了什麼,以糾正「savePath」減速或「temp = os.path.join(savePath,files)」內的使用內發現的錯誤?

def printTime(time): 
    savePath = "C:\Users\Nicholas\Documents" 
    files = open("LogInLog.txt", "a") 
    temp = os.path.join(savePath, files) 
    files.write("A LogIn occured.") 
    files.write(time) 
    print files.read 
    files.close 

main() 

整個程序如下供參考:

from time import strftime 
import os.path 

def main(): 
    getTime() 

def getTime(): 
    time = strftime("%Y-%m-%d %I:%M:%S") 
    printTime(time) 

def printTime(time): 
    savePath = "C:\Users\Nicholas\Documents" 
    files = open("LogInLog.txt", "a") 
    temp = os.path.join(savePath, files) 
    files.write("A LogIn occured.") 
    files.write(time) 
    print files.read 
    files.close 

main() 
+1

你應該參考https://docs.python.org/2/library/logging.html – pigletfly

+0

不是一個問題「事情是內'printTime()'函數走錯了」,至少說_what_出錯了。 – Julien

+0

對不起編輯我的問題......認爲它是自我解釋性的,我正在嘗試做...但我沒有使用「import os.path」導入太多,並且無法嘗試將文件保存在代碼 –

回答

1

這裏有一個工作版本:

from time import strftime 
import os.path 

def main(): 
    getTime() 

def getTime(): 
    time = strftime("%Y-%m-%d %I:%M:%S") 
    printTime(time) 

def printTime(time): 
    savePath = "C:\Users\Nicholas\Documents" 
    logFile = "LogInLog.txt" 
    files = open(os.path.join(savePath, logFile), "a+") 
    openPosition = files.tell() 
    files.write("A LogIn occured.") 
    files.write(time) 
    files.seek(openPosition) 
    print(files.read()) 
    files.close() 

if __name__ == '__main__': 
    main() 

有幾個問題張貼在問題的代碼片段:

  1. Two import st節點被連接在一起。每個應該在一個單獨的行。

  2. os.path.join函數在打開的文件句柄上不起作用。

  3. read()close()方法丟失了parens。

  4. 如果打算讀什麼書是寫在追加模式,有必要通過tell()seek()得到當前文件位置,該位置寫入文件。

  5. 儘管在沒有任何條件檢查的情況下調用main()是合法的,但通常最好確保將模塊調用爲腳本而不是導入。

+0

內的目錄執行完美,正如我想要的...並感謝您的崩潰,它肯定會幫助我的這個計劃的未來。還有一件事,因爲我發現.pcf(python編譯的文件)在啓動windows時不能正確執行,我一直在研究如何使用pyinstaller,並且在解決如何在我的.py中真正運行pyinstaller時遇到困難文件創建一個獨立的.exe文件,以便Windows可以運行該文件沒有問題。有什麼建議麼? –

+0

非常歡迎。我對Windows平臺並不是很熟悉,所以除了在堆棧溢出中打開另一個問題之外,我無法爲你的'pyinstaller'問題提供任何建議。祝你好運! –