<
>

Python打开文件、文件读写操作、with方式、文件常用函数实例分析

2020-06-25 08:10:20 来源:易采站长站 作者:易采站长站整理

-----------
运行结果:
my

readlines()是读出全部内容,并整理成一个列表


print("r".center(50,'-'))
f=open("file.txt",encoding="utf-8")
print(f.readlines())
f.close()

#------------------------r-------------------------
#运行结果:
['myn', 'sasn', 'aaan', 'fsafsan', '中文n', '中文n', '葫芦娃n', 'n']

r+模式会根据读的内容来决定指针的位置


print("r".center(50,'-'))
f=open("file.txt","r+",encoding="utf-8")
# print(f.readline())
f.write("hello mike")
f.close()

结果:

image

 


print("r".center(50,'-'))
f=open("file.txt","r+",encoding="utf-8")
print(f.readline())
f.write("hello mike")
f.close()

新结果:

image 

写操作:

write():将一个字符串写入文件


myfile=open("myfile1","wb")
myfile.write(b"nnnnnn")
myfile.write("my葫芦娃".encode("utf-8"))
myfile.close()

writelines(可迭代对象) 将一个可迭代对象写入文件


myfile=open("myfile1","wb")
myfile.write(b"nnnnnn")

myfile.writelines([b'1',b'2',b'3',b'4'])
myfile.close()

当需要写完之后即时读出来时,使用w+,然后将文件指针置回文件头:


myfile=open("myfile1","wb+")
myfile.write(b"nnnnnn")
myfile.seek(0)
print(myfile.read())
myfile.close()

如果是需要读出特定位置,可以使用变量来记录位置


myfile=open("myfile1","wb+")
myfile.write(b"1nnnnnn")
site=myfile.tell()
myfile.write(b"2nnnnnn")
myfile.seek(site)##读出后一段
print(myfile.read())
myfile.close()


with:

为了便捷的关闭文件,python增加了with功能,当with体执行完将自动关闭打开的文件:


with open("file.txt","r+",encoding="utf-8") as f:##将自动执行f.close()
print(f.tell())
f.write("金刚")
for line in f:
print(line,end="")

可以同时打开多个文件:


with open("file.txt",'r') as f ,
open("file.new",'r') as m:
print(f.read(),m.read())


文件常用函数:

file.close():关闭文件。关闭后文件不能再进行读写操作

暂时禁止评论

微信扫一扫

易采站长站微信账号