python文件读取和创建

方法一:

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

 

 

 

 



posted @ 2020-03-18 21:08  爬爬QQ  阅读(321)  评论(0)    收藏  举报