简体   繁体   English

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

[英]How do I create a text file through python?

I have no idea why this isn't working 我不知道为什么这不起作用

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)

I want to be able to simply create a text file and write in it with the the text file's name as today's date. 我希望能够简单地创建一个文本文件并以文本文件的名称作为今天的日期写入其中。 The "w" doesn't seem to be creating the file. “ w”似乎并未创建文件。 I am getting the error: 我收到错误消息:

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

You seem to be running this on an operating system where / is a directory separator. 您似乎正在/是目录分隔符的操作系统上运行此命令。

Try this code instead: 请尝试以下代码:

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)

Note a few things: 请注意以下几点:

  • using with is much better practice, as it guarantees your file is closed, even if an exception occurs 使用with是更好的做法,因为即使出现异常,它也可以确保关闭文件
  • it is bad practice to use file for your file name 使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM