python day03 IO初探
文件读写:
>>> contact = file("contact_list.txt")
>>> contact.read() #读取全部
'1\tbill\t18\thunan\n2\tlulu\t10\tzhuzhou\n3\tfly\t10\tchenzhou\n'
>>> contact = file("contact_list.txt")
>>> contact.readline() #读取单行
'1\tbill\t18\thunan\n'
>>> contact.readline()
'2\tlulu\t10\tzhuzhou\n'
>>> contact.readline()
'3\tfly\t10\tchenzhou\n'
>>> contact.readline() #读完则无
''
>>> contact.readline()
''
>>> contact = file("contact_list.txt")
>>> lines = contact.readlines() #读取出为一个列表
>>> for line in lines:
... print line, #打印时带上,会去掉\n
...
1 bill 18 hunan
2 lulu 10 zhuzhou
3 fly 10 chenzhou
>>>
f = file(“filePath”,”w”) # 若文件不存在,则创建。若存在则覆盖
f = file(“filePath”,”a”) # 若文件不存在,则创建。若存在则追加
名称查找小程序:
#!/usr/bin/env python
import sys
contact_list = "contact_list.txt"
f = file(contact_list)
c = f.readlines()
while True:
user_input = raw_input("\033[32;1mPlease input str to search:\033[0m").strip()
if len(user_input) != 0:
for line in c:
if user_input in line:
print line
break
elif user_input == "q" or user_input == "quit":
print "\033[31;1mByebye ~\033[0m"
sys.exit()
else:
print "\033[31;1mnot a valid key word!\033[0m"
1 bill 18 hunan
2 lulu 10 zhuzhou
3 fly 10 chenzhou