python将数据写入txt

python将数据写入txt文本文件:首先打开txt文件;然后向文件写入数据,代码为【file_handle.write(‘hello word 你好 \n’);file_handle.writelines(…)】

本教程操作环境:windows7系统、python3.9版,DELL G3电脑

python将数据写入txt文本文件:

1、打开txt文件
file_handle=open('1.txt',mode='w')
上述函数参数有(1.文件名,mode模式)

mode模式有以下几种:
#w 只能操作写入 r 只能读取 a 向文件追加

#w+ 可读可写 r+可读可写 a+可读可追加

#wb+写入进制数据

#w模式打开文件,如果而文件中有数据,再次写入内容,会把原来的覆盖掉

2、向文件写入数据

第一种写入方式:
  2.1  write:写入

#\n 换行符

file_handle.write('hello word 你好 \n')

第二种写入方式:
  2.2  writelines()函数 会将列表中的字符串写入文件中,但不会自动换行,如果需要换行,手动添加换行符

#参数 必须是一个只存放字符串的列表

file_handle.writelines(['hello\n','world\n','你好\n','智游\n','郑州\n'])

3、关闭文件

file_handle.close()

你可能感兴趣的:(python写入日志)