文件 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 )

