Python 使用 with open 写入系统时间到文件
要在 Python 中使用 'with open' 来写入系统时间,你可以使用 'datetime' 模块来获取当前的系统时间,然后将其写入文件。
下面是一个示例代码:
from datetime import datetime
# 获取当前系统时间
now = datetime.now()
# 将时间格式化为字符串
formatted_time = now.strftime('%Y-%m-%d %H:%M:%S')
# 打开文件并写入时间
with open('file.txt', 'w') as file:
file.write(formatted_time)
在上面的示例中,我们首先导入 'datetime' 模块,然后使用 'datetime.now()' 函数获取当前系统时间。然后,我们使用 'strftime()' 方法将时间格式化为字符串,其中 '%Y-%m-%d %H:%M:%S' 是时间的格式。
接下来,我们使用 'with open' 语句打开文件(在此示例中为 'file.txt'),并将其赋值给变量 'file'。然后,我们使用 'write()' 方法将格式化的时间写入文件。
请注意,在使用 'with open' 语句时,不需要显式地关闭文件,因为 'with' 语句会自动处理文件的打开和关闭。
原文地址: https://www.cveoy.top/t/topic/wrg 著作权归作者所有。请勿转载和采集!