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

时间:2016-03-01 22:55:21

标签: 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'

2 个答案:

答案 0 :(得分: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是更好的做法,因为它可以保证您的文件已关闭,即使发生异常也是如此
  • mysql> select fieldnames from tablename limit 5; +--------------------------------------------------------+ | fieldnames | +--------------------------------------------------------+ | {"example-field-1": "val2"} | | {"example-field-2": "val1"} | | {"example-field-1": "val1", "example-field-3": "val1"} | | {"example-field-2": "val1"} | | {"example-field-2": "val2"} | +--------------------------------------------------------+ mysql> select JSON_EXTRACT(fieldnames, '$.example-field-1') from tablename; ERROR 3143 (42000): Invalid JSON path expression. The error is around character position 17 in '$.example-field-1'. 用于您的文件名
  • 是不好的做法

答案 1 :(得分: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)