python(如何将数据写⼊本地txt⽂本⽂件)⼀、读写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()
⼆、读取txt⽂件
1、打开⽂件
#使⽤r模式打开⽂件,做读取⽂件操作
#打开⽂件的模式,默认就是r模式,如果只是读⽂件,可以不填写mode模式
file_handle=open('1.txt',mode='r')
2、读取⽂件内容
第⼀种读取⽅式:
#2.1 read(int)函数,读取⽂件内容。如果指定读取长度,会按照长度去读取,不指定默认读取所有数据
# content=ad(20)
# print(content)
第⼆种读取⽅式:
writelines()方法将什么写入文件#2.2readline(int)函数默认读取⽂件⼀⾏数据
content=adline(20)
print(content)
第三种读取⽅式:
#2.3 readlines()  会把每⼀⾏的数据作为⼀个元素放在列表中返回,读取所有⾏的数据
contents=adlines()
print(contents)
3、关闭⽂件
file_handle.close()
————————————————
原⽂链接:blog.csdn/huo_1214/article/details/79153847