2016-03-01 32 views
0

我不知道這是爲什麼不工作如何通過python創建文本文件?

import time 

consumption = "300" 
spend = "5000" 

def create_report(consumption, spend): 

    date = time.strftime("%d/%m/%Y") 
    date = date + ".txt" 
    file = open(date, "w") 
    file.write("Since: ", pastdate) 
    file.write("Consumption in £: ", consumption) 
    file.write("Overall spend in £: ", spend) 
    file.close() 

create_report(consumption, spend) 

我希望能夠簡單地創建一個文本文件,並在它與今天的日期文本文件的名字寫。 「w」似乎沒有創建文件。我得到的錯誤:

file = open(date, "w") 
FileNotFoundError: [Errno 2] No such file or directory: '01/03/2016.txt' 
+0

這不是您平臺上的有效文件名。 – jonrsharpe

+0

使用'date = time.strftime(「%d-%m-%Y」)'作爲替代 – gtlambert

+0

嘗試'w +'而不是'w',看看是否可以解決您的問題。 –

回答

0
import time 

consumption = "300" 
spend = "5000" 

def create_report(consumption, spend): 
    # '/' is used for path like `C:/Program Files/bla bla` so you can't use it as a file name 
    date = time.strftime("%d_%m_%Y") 
    date = date + ".txt" 
    file = open(date, "w") 
    # NameError: name 'pastdate' is not defined 
    # file.write("Since: ", pastdate) 

    # The method `write()` was implemented to take only one string argument. So ',' is replaced by '+' 
    file.write("\n Consumption in £: " + consumption) 
    file.write("\n Overall spend in £: " + spend) 
    file.close() 

create_report(consumption, spend) 
0

你似乎操作系統,其中/是一個目錄分隔上運行此。

試試這個代碼,而不是:

date = time.strftime("%d%m%Y") + '.txt' 
with open(date, "w") as f: 
    f.write("Since: ", pastdate) 
    f.write("Consumption in £: ", consumption) 
    f.write("Overall spend in £: ", spend) 

注意的幾件事情:

  • 使用with是更好的做法,因爲它保證你的文件被關閉,即使發生異常
  • 使用file作爲文件名是不好的做法
相關問題