1、文件的打开,关闭及读写操作
打开:f=open(文件目录、文件操作符) 、with open() as f
关闭:f.close()
读写:f=open("test.txt”,"r")、f=open(“test.txt",”w”)
2、有一个test.txt文件,以只读的方式打开此文件,用变量f接收文件打开的返回值.
f=open(“test.txt”,"r")
3、文件访问模式中r表示什么模式,r+表示什么模式?有什么区别?
r只读 r+读写 文件指针都在文件开始的位置
4、文件访问模式中w表示什么模式,w+表示什么模式?
w写 w+读写
5、文件操作中要在文件中追加改如何操作?
open(“test.txt”,"a")
6、如何关闭一个文件?
使用file.close()语句
7、将打开的test.txt文件关闭,用变量f接收返回值.
f=close()返回值是None
8、请在test.txt文件中写入"wow,so beautiful!".
f=open(“test.txt”,”w”)
f.write("wow,so beautiful!”)
f.close()
9、创建一个文件,把文件复制一遍——no
# 创建一个文件
with open("gailun.txt","w") as f:
f.write("德玛西亚,人在塔在")
# 把文件复制一遍
with open("gailun.txt","r",encoding='utf-8') as f:
while True:
index=f.name.find('.')
# 获取文件名
file_name=f.name[:index]+'副本'+f.name[index:]
# 读取文件内容
content=f.readline()
# 判断文件是否读完
if len(content)==0:
break
else:
# 写入内容
wf=open(file_name,'w',encoding='utf-8')
wf.write(content)
10、建立read.txt文件。
在此文件中写入"hello world! hello python!hello everyone!"
打开文件,读取5个字符。
查找当前位置,并格式化输出。
把指针重新定位到文件的开头读取10个字符串。
关闭文件
我的答案:
f=open("read.txt","w")
f.write("hello world! hello python!hello everyone!")
f.close()
f=open("read.txt","r")
content=f.read(5)
print(content)
print("当前位置为:",f.tell())
f.seek(0,0)
print(f.read(10))
f.close()
官方答案:
f = open("read.txt","w")
f.write("hello python! hello everyone! hello world!")
f.close()
f = open("read.txt","r")
content = f.read(5)
print(content)
print("当前位置为:",f.tell())
f.seek(10,0)
print(f.read())
f.close()