Loading

Python按行读取文件、写文件

Python按行读取文件

查找了几个文件读取的写法,整理如下:

学习了:https://www.cnblogs.com/scse11061160/p/5605190.html

 

file = open("sample.txt") 
for line in file:
    pass # do something
file.close()

 

学习了:https://blog.csdn.net/ysdaniel/article/details/7970883

去除换行符

for line in file.readlines():  
     line=line.strip('\n')  

 

学习了:https://www.cnblogs.com/feiyueNotes/p/7897064.html

mobile = Method.createPhone()
file = r'D:\test.txt'
with open(file, 'a+') as f:
     f.write(mobile+'\n')   #加\n换行显示

 

'r':读
'w':写
'a':追加
'r+' == r+w(可读可写,文件若不存在就报错(IOError))
'w+' == w+r(可读可写,文件若不存在就创建)
'a+' ==a+r(可追加可写,文件若不存在就创建)
对应的,如果是二进制文件,就都加一个b就好啦:
'rb'  'wb'  'ab'  'rb+'  'wb+'  'ab+'

 

posted @ 2018-05-27 07:06  stono  阅读(83952)  评论(3编辑  收藏  举报