python进阶(3)——文件

打开文件:(非当前目录需指定完整路径)

f = open('lcctry.py')

读取和写入:

f = open('lcctry.txt','w')

f.write('hello, world')
Out[130]: 12

f.close()

读取时的r可以不写,调用open时默认为r

f=open('lcctry.txt','r')

f.read(3)
Out[2]: 'hel'

f.read()
Out[3]: 'lo, world'

f.read()
Out[4]: ''

读取行:

some_file.readline()读取一整行并返回

some_file.readline(5)最多读取5个字符并返回

关闭文件:

1 close

2 try与finally

#打开文件
try:
#将数据写入文件
finally:
file.close()

3 with语句(在语句末尾时将自动关闭文件)

with open(“somefile.txt") as somefile:
    do_something(somefile)

f=open('lcctry.txt','w')
f.write('this\nis no\nhaiku')
f.close()
#不加最后的close()时发现文字没有被添加进lcctry.txt

猜你喜欢

转载自blog.csdn.net/weixin_40725491/article/details/83064766