Python_文件写入数据案例

# 写入数据
filename = 'my.txt'
with open(filename,'w',encoding='utf-8') as file:
    len = file.write("Python is very good !")
    print(f"成功写入文件,长度是{len}")

filename2 = "我的文档.txt"
# 写入多行数据
with open(filename2,'w',encoding='utf-8') as f2:
    f2.write("Python是最好的编程语言!\n")
    f2.write("Python 功能强大!\n")

# 追加写入
with open(filename2,'a',encoding='utf-8') as f2:
    f2.write("新增一行!")

# 使用writelines
filename3 = 'my3.txt'
with open(filename3,'w',encoding='utf-8') as file3:
    # 生成字符串
    lst = ['床前明月光,\n','疑是地上霜。\n','举头望明月,\n','低头思故乡。']
    file3.writelines(lst)

该案例下载地址

蓝奏云下载