如何通过python创建文本文件?

2024-05-16 07:23:10 发布

您现在位置: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'

Tags: inimportreporttxtdatetimedefcreate
2条回答

您似乎是在一个操作系统上运行这个命令,/是一个目录分隔符。你知道吗

请尝试以下代码:

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作为文件名是不好的做法
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)

相关问题 更多 >