【问题标题】:Struggling with Files [duplicate]与文件斗争[重复]
【发布时间】:2017-09-20 20:17:00
【问题描述】:

我目前正在做一个项目,我需要制作一个文本文件。但是python程序没有生成文件我已经搜索了很多论坛并尝试了所有我不知道发生了什么的事情。我在下面包含了代码和错误消息。

import time
import sys 
import os
import datetime
from pathlib import Path

cont = True
nows = time.strftime("%d/%m/%Y %H:%M")
tst = datetime.datetime.now().isoformat("-").split(".")[0].replace(":","-")
f = open("LOG %s.txt" % nows, "w+")
f.write('Start time, End time, Callsign, Report, Report sent, Serial, locator, comments')

while cont == True:
    now = datetime.datetime.now()
    callsign = input("Callsign : ")
    start = now
    print(now)
    rst_rc = input("Signal report recived: ")
    rst_st = input("Signal report semt: ")
    ser = input("Serial number: ")
    loc = input("Locator: ")
    comment = input("Comments: ")
    end = now
    print(now)
    f.write(start, end, callsign, rst_rc, rst_st, ser, loc, comment)

contin = input("Do you want another call? ")
if contin == "y":
    cont = False
    sys.exit()

以下是我得到的错误:

traceback (most recent call last):
  File "/Users/thomasscott/Desktop/Py-qso/py-qso.py", line 10, in <module>
    f = open("LOG %s.txt" % nows, "w+")
FileNotFoundError: [Errno 2] No such file or directory: 'LOG 20/09/2017 21:08.txt'

【问题讨论】:

  • 您的日期可能被解释为目录路径,即“'LOG 20/09/2017 21:08.txt'` 被解释为 LOG /20/09作为文件路径.
  • 所以,简单的解决方案,使用nows = time.strftime("%d-%m-%Y %H:%M")。此外,在终止程序之前,您需要 .close() 您的,否则您可能不会在缓冲区中写入所有内容。
  • 是的,我将其作为一个 shell 问题的副本关闭,但它具有完全相同的潜在问题。
  • 好的,感谢您将其标记为重复。我找不到与我道歉的相同问题的其他问题。

标签: python file


【解决方案1】:

正如@juanpa 指出的那样,您的日期被解释为路径,因此它会尝试打开目录“LOG 20/09/”中名为“2017 21:08.txt”的文件。要解决此问题,只需在第 8 行的 strftime 调用中将“/”替换为“_”。此外,我不认为打开模式“w+”可以创建文件。只需使用“w”即可。

【讨论】:

    猜你喜欢
    • 2021-04-30
    • 2021-03-22
    • 1970-01-01
    • 2015-12-07
    • 2017-06-22
    • 2020-09-18
    • 2018-05-23
    • 2013-11-08
    • 1970-01-01
    相关资源
    最近更新 更多