python day03 IO初探

python day03 IO初探

文件读写:
    
  1. >>> contact = file("contact_list.txt")
  2. >>> contact.read() #读取全部
  3. '1\tbill\t18\thunan\n2\tlulu\t10\tzhuzhou\n3\tfly\t10\tchenzhou\n'
  4. >>> contact = file("contact_list.txt")
  5. >>> contact.readline() #读取单行
  6. '1\tbill\t18\thunan\n'
  7. >>> contact.readline()
  8. '2\tlulu\t10\tzhuzhou\n'
  9. >>> contact.readline()
  10. '3\tfly\t10\tchenzhou\n'
  11. >>> contact.readline() #读完则无
  12. ''
  13. >>> contact.readline()
  14. ''
  15. >>> contact = file("contact_list.txt")
  16. >>> lines = contact.readlines() #读取出为一个列表
  17. >>> for line in lines:
  18. ... print line, #打印时带上,会去掉\n
  19. ...
  20. 1 bill 18 hunan
  21. 2 lulu 10 zhuzhou
  22. 3 fly 10 chenzhou
  23. >>>

    f = file(“filePath”,”w”)  # 若文件不存在,则创建。若存在则覆盖
    f = file(“filePath”,”a”)   # 若文件不存在,则创建。若存在则追加
名称查找小程序:
  1. #!/usr/bin/env python
  2. import sys
  3. contact_list = "contact_list.txt"
  4. f = file(contact_list)
  5. c = f.readlines()
  6. while True:
  7. user_input = raw_input("\033[32;1mPlease input str to search:\033[0m").strip()
  8. if len(user_input) != 0:
  9. for line in c:
  10. if user_input in line:
  11. print line
  12. break
  13. elif user_input == "q" or user_input == "quit":
  14. print "\033[31;1mByebye ~\033[0m"
  15. sys.exit()
  16. else:
  17. print "\033[31;1mnot a valid key word!\033[0m"
  1. 1 bill 18 hunan
  2. 2 lulu 10 zhuzhou
  3. 3 fly 10 chenzhou

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注