Python print输出到txt文档和输出年月日时分秒
来源:网络收集 点击: 时间:2024-02-25第一,print()输出到txt文档。运行下列代码,就可以把“Where there is a will, there is a way”输入到txt文档中。
fileone = open(rD:\test.txt,a+)print(Where there is a will, there is a way,file=fileone)fileone.close()

第二,运行上述代码,在D盘中就会找到名为test的txt文档,“Where there is a will, there is a way”就输入到了该文档中。

第三,如果输出年份,这需要调用datetime模块。运行下列代码,可以将当前年份输出出来。
import datetimefiletwo = open(rD:\test.txt,a+)print(当前年份:+str(datetime.datetime.now().year),file = filetwo)filetwo.close()

第四,保存和运行上述代码,当前年份就输出到了test.txt中。

第五,要想输入年月日和时分秒,只需要在上述代码的基础的增加如下代码:
print(当前日期时间:+datetime.datetime.now().strftime(%Y-%m-%d %H:%M:%S),file = filetwo)

第六,保存和运行上述代码,年月日时分秒就输出到了test.txt中。其中年月日%Y-%m-%d和时分秒%H:%M:%S的格式一定注意大小写奥,像这样才可以。

版权声明:
1、本文系转载,版权归原作者所有,旨在传递信息,不代表看本站的观点和立场。
2、本站仅提供信息发布平台,不承担相关法律责任。
3、若侵犯您的版权或隐私,请联系本站管理员删除。
4、文章链接:http://www.1haoku.cn/art_152684.html