用python操作文件

一般情况下会对文件进行的操作
1、找到文件,打开文件:f = open(filename)
2、读取、修改:f.read() f.write()
3、保存、关闭文件:f.close()

注意:文件只能以一种模式打开,分别有三种模式:

r read
w write 创建新文件的模式
a append

(1)w创建模式
创建student.txt文件,并打开,写入学生信息

>>>f=open(file='D:\迁移文件\python\students.txt',mode="w")
>>>f.write("kitty  218923   score 90\n")
>>>f.write("zero  218924   score 60\n")
>>>f.close()

结果:
在这里插入图片描述在这里插入图片描述
(2)r只读模式

>>>f=open('D:\迁移文件\python\students.txt',mode="r")
>>>print(f.readline())  #读一行
>>>print("----分隔符----")
>>>data=f.read()   #读剩下所有的内容,括号里可以写数字,表示打印前多少的内容
>>>print(data)
>>>f.close()
kitty  218923   score 90

----分隔符----
zero  218924   score 60
miao 213144   score 87
max  218363   score 56

(3)a追加模式

>>>f=open('D:\迁移文件\python\students.txt',mode="a")
>>>f.write("cheery 682168  score  88")  #会追加在文件最后面
>>>f.close()

结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Kittymiaomiao/article/details/109001011