如何显示文件名(创建后)。例如文件名…txt
from datetime import datetime
default_name_begining_of_the_file = "Investment_result_"
savereport = input("Save result to text file? ")
if savereport in ["y", "yes", "YES"]:
nameoffileinput = (input("Name of begining of the file: ") or default_name_begining_of_the_file)
generatedatetime = datetime.now().strftime("%Y_%m_%d-%I%M%S_%p")
open(f'{nameoffileinput}_{generatedatetime}.txt', 'w')
else:
print(f"Result will not be written to text file.")
在open(f'{nameoffileinput}_{generatedatetime}.txt', 'w')
之前加上print
例如:
from datetime import datetime
default_name_begining_of_the_file = "Investment_result_"
savereport = input("Save result to text file? ")
if savereport in ["y", "yes", "YES"]:
nameoffileinput = (input("Name of begining of the file: ") or default_name_begining_of_the_file)
generatedatetime = datetime.now().strftime("%Y_%m_%d-%I%M%S_%p")
file_name = f'{nameoffileinput}_{generatedatetime}.txt'
print(f"The name of written file is : {file_name}")
with open(file_name, 'w') as f:
pass # do stuff...
else:
print(f"Result will not be written to text file.")
另外,用with
语句关闭open()
部分效果更好。