0

我正在尝试这样的事情。

data = "test data" + '\n'

now = datetime.now() 

now = str(now)

f1 = str((now).split(" ") [0])

f2 = "macaddress"

file_name = f1 + '_' + f2

fout = open(file_name,'a+')

while 1:
   fout.write("data")

文件已成功创建,当前日期为文件名,数据已写入文件。但是我遇到的问题是,如果我检查文件是否存在,则表明该文件不存在,即使该文件存在。

我试图检查存在使用if(os.path.isfile(file_name)):

4

1 回答 1

0

您不需要将日期时间拆分为字符串。使用 f 字符串会更容易(确保格式化它)。例如,我将创建一个以日期为名称的文本文件。

import datetime
import os

filestream = "yourpathhere"
docdate = f"{datetime.datetime.now().strftime('%m-%d-%Y')}"

filetype = ".txt"

path = f"{filestream}{docdate}{filetype}"

with open(path, "w") as file:
    mymessage = f"Hello, I am a text file!"

    # Write to the newly created file
    file.write(mymessage)
    
    # Close the opened file #
    file.close()

您可以使用该isfile()方法检查文件是否存在。

if (os.path.isfile(path)):
    print("The file:", path, "has already been created")
于 2020-07-19T06:33:08.557 回答