python实现如何将单行或者多行内容写入到文件

涉及到文件写入有很多种方式,这里简单介绍一种,

Talk is cheap,show me the code.

# 文件写入example

#example1--------假如你要写入一行数据:
line_str = f'example1: hello world!\n'
with open('txt.txt','w') as f:
    f.writelines(line_str)

#example2--------假如你要写入多行数据:
str_list = []
line1 = f'example2: python!\n'
line2 = f'example2: code!\n'
str_list.append(line1)
str_list.append(line2)
with open('txt.txt','a') as f:
    f.writelines(str_list)

有问题随时联系,欢迎一键三连!

你可能感兴趣的:(python,python)