如何在 Python 中添加今天的日期和时间的同时询问文件名?

How to ask for filename whilst adding today's date and time in Python?

我已经编写了自动创建日期和时间格式文件的代码。因此,文件输出将是

Product_Name-date

来自这段代码:

filename = datetime.now().strftime('Product_Name-%Y-%m-%d-%H-%M.csv')
with open(filename, "w+") as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(["Name", "Price"])
    for d in datas: csv_output.writerow(d)

但是,我想请求用户输入以手动命名每个文件。成为:

UserInputProduct_Name-日期

我已经阅读了W3School的教程,但我无法正确实施。

 filename = input("Input the Filename: ")
 f_extns = filename.split(".")
 print ("The extension of the file is : " + repr(f_extns[-1]))

我该怎么做?

这是你想要的吗?

Product_Name = input("Input the Filename: ")
filename = datetime.now().strftime(f'{Product_Name}-%Y-%m-%d-%H-%M.csv')
with open(filename, "w+") as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(["Name", "Price"])
    for d in datas: csv_output.writerow(d)

我不确定我是否答对了你的问题,但我想这就是你要找的。

Product_Name = input("Enter filename: ")
filename = datetime.now().strftime('{}-%Y-%m-%d-%H-%M.csv').format(Product_Name)
with open(filename, "w+") as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(["Name", "Price"])
    for d in datas:
        csv_output.writerow(d)

自己测试这段代码后,我得到了名为:

的文件

test-2021-07-03-16-30.csv

bera TV 已经回答了,这就是根据你第一个问题的解决方案

我假设你的第二个问题是“获取文件的扩展名”

可能与 this question

重复

作为解决方案,您可以使用 python 3.x

中可用的路径库
>>> import pathlib
>>> x = pathlib.PurePosixPath("C:\Path\To\File\myfile.exten").suffix
>>> print(x)
".exten"