Python 写入txt文本文件

时间:2025-05-07 17:15:40

引入

#自带os库,用于获取绝对路径
import os

完整示例

import os
 
if __name__ == '__main__':
    #异常捕获
    try:
        #获取绝对路径
        path = os.path.dirname(os.path.realpath(__file__))
        print('获取到的路径:'+path)
        
        text = '我是内容'
        
        #文件写入的路径
        path = path +'/text.txt'
        with open(path,'w') as f:
             f.write(text);
        
    
    except Exception as e:
        print(e)
    input()

我的其他文章

亲身分享 一次 字节跳动 真实面试经历和面试题