python 打开文件--读取文件内容,并判断控制,并切分字符串
文件 runoob.txt 的内容如下:
1:www.runoob.com
2:www.runoob.com
3:www.runoob.com
4:www.runoob.com
5:www.runoob.com
readlines() 方法用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for... in ... 结构进行处理。
如果碰到结束符 EOF 则返回空字符串。
writelines() 方法用于向文件中写入一序列的字符串。
这一序列字符串可以是由迭代对象产生的,如一个字符串列表。
换行需要制定换行符 \n。
#!/usr/bin/python # -*- coding: UTF-8 -*-
# 打开文件
fo = open("runoob.txt", "r")
print "文件名为: ", fo.name
for line in fo.readlines():
#依次读取每行
if line.strip()=='':
continue
line = line.strip() #去掉每行头尾空白
print "读取的数据为: %s" % (line)
# 关闭文件
fo.close()
list=[]
with open('/Users/goboy/Documents/runboo.txt', 'r') as f:
file_read=f.readlines()
for readline in file_read:
if readline.strip()=='':
continue
url=readline.split('//')[1]
list.extend(url)
with open('/Users/goboy/Documents/runboo2.txt', 'x') as f:
f.writelines( list )