码迷,mamicode.com
首页 > 编程语言 > 详细

python文件读取和创建

时间:2020-03-18 21:48:29      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:and   uid   none   ret   lap   news   new   pat   strip()   

方法一:

path=‘d:/NEWS.txt‘
#以写模式打开路径文件,若不存在则创建,存在则覆盖,写入nihao
f=open(path,‘w‘)
f_name.write(‘NIHAO‘)
#以读模式打开路径文件
f_name=open(path,‘r‘)
#读取文件
f_name.read()
#以添加模式创建,存在则添加,不存在则创建
f_name=open(path,‘a‘)
f_name.write(‘\nNIHAO,hello world‘)

  如果使?open创建?件对象,?定要?close关闭它。关闭?件
  可以返回操作系统资源:

  f.close()

方法二:

path=‘d:/NEWS.txt‘
In [212]: with open(path) as f:
.....: lines = [x.rstrip() for x in f]
这样可以在退出代码块时,?动关闭?件。

常用示例:

技术图片
In [225]: with open(‘tmp.txt‘, ‘w‘) as handle:
.....: handle.writelines(x for x in open(path) if len(x) In [226]: with open(‘tmp.txt‘) as f:
.....: lines = f.readlines()
In [227]: lines
Out[227]:
[‘Sueña el rico en su riqueza,\n‘,
‘que más cuidados le ofrece;\n‘,
‘sueña el pobre que padece\n‘,
‘su miseria y su pobreza;\n‘,
‘sueña el que a medrar empieza,\n‘,
‘sueña el que afana y pretende,\n‘,
‘sueña el que agravia y ofende,\n‘,
‘y en el mundo, en conclusión,\n‘,
‘todos sueñan lo que son,\n‘,
‘aunque ninguno lo entiende.\n‘]
View Code

技术图片

 

 技术图片

 

 



python文件读取和创建

标签:and   uid   none   ret   lap   news   new   pat   strip()   

原文地址:https://www.cnblogs.com/lianghaiming/p/12520229.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!