python怎么逐行读写txt文件

php中世界最好的语言
php中世界最好的语言 原创
2018-04-09 10:11:18 9792浏览

这次给大家带来python怎么逐行读写txt文件,python逐行读写txt文件的注意事项有哪些,下面就是实战案例,一起来看一下。

实例如下所示:

# -*-coding:utf-8-*-
import os
file_obj = open("test2.txt")
all_lines = file_obj.readlines()
for line in all_lines:
  print line
file_obj.close()
# 写之前,先检验文件是否存在,存在就删掉
if os.path.exists("dest.txt"):
  os.remove("dest.txt")
mylist = ["luoluo", "taotao", "mumu"]
# 以写的方式打开文件,如果文件不存在,就会自动创建
file_write_obj = open("dest.txt", 'w')
for var in mylist:
  file_write_obj.writelines(var)
  file_write_obj.write('\n')
file_write_obj.close()

w 以写方式打开,

a 以追加模式打开

r+ 以读写模式打开

w+ 以读写模式打开

a+ 以读写模式打开

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

python字符串如何转为二维数组

Event emitter的监听事件

以上就是python怎么逐行读写txt文件的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。