python知识框架

  1. 常量,变量,运算符,分支和循环
  2. 数据结构,函数
  3. 文件
  4. 模块,包

1. 文件:打开,读写,关闭

1.1. 文件对象:class '_io.TextIOWrapper'

1.2. 文件方法:

  • open("file_name")

    • r:只读,文件指针在开头
    • w:覆盖,只写,文件指针在开头
    • a:不覆盖,只写,文件指针在结尾
    • r+/w+/a+:以读写方式打开(频繁移动文件指针会降低读写效率,因此很少使用该属性)
  • file.read()

    • 文件指针:打开时指针在开头或结尾,读写时指针移动,关闭后指针恢复

    • ```python

      文件较大时可采用while+readline来读取文件

      file = open(“hello.txt”)

while True: txt_line = file.readline()
print(txt_line) if not txt_line: break

file.close()

  1. -
  2. `file.write()`
  3. -
  4. `file.close()`
  5. > 实战案例:文件复制
  6. > ```python
  7. #--------------小文件读写------------------#
  8. # 1.打开文件
  9. rfile = open("hello")
  10. wfile = open("empty_file","w")
  11. # 2.读hello.txt,写到empty_file.txt
  12. message = rfile.read()
  13. wfile.write(message)
  14. # 3.关闭文件
  15. rfile.close()
  16. wfile.close()
  17. #----------------大文件读写----------------#
  18. # 1.打开文件
  19. rfile = open("hello")
  20. wfile = open("empty_file","w")
  21. # 2.读hello 写到empty_file
  22. while True:
  23. message = rfile.readline()
  24. wfile.write(message)
  25. if not message:
  26. break
  27. # 3.关闭文件
  28. rfile.close()
  29. wfile.close()

1.3. 标准打开读写关闭:with ... as ...:

  • with … as …自动关闭文件
  1. with open('/path/to/file', 'r') as f:
  2. print(f.read())
  3. '''
  4. try:
  5. f = open('/path/to/file', 'r')
  6. print(f.read())
  7. finally:
  8. if f:
  9. f.close()
  10. '''
  1. with open('/Users/michael/test.txt', 'w') as f:
  2. f.write('Hello, world!')
  3. '''
  4. f = open('/Users/michael/test.txt', 'w')
  5. f.write('Hello, world!')
  6. f.close()
  7. '''

补充:

1. print:格式化输出%

  1. user = "Charli"
  2. age = 8
  3. # 格式化字符串有两个占位符,第三部分提供2个变量
  4. print("%s is a %s years old boy" % (user , age))

2. function:def

  1. def functionname( parameters ):
  2. "函数_文档字符串"
  3. function_suite
  4. return [expression]

3. class:class ClassName:

  1. class Employee:
  2. def displayCount(self):
  3. print "Total Employee %d" % Employee.empCount

4. eval()函数:evaluate—-IDE中实现交互

案例实战:小型计算器

  1. input_str = input("please enter a expression: ")
  2. print(eval(input_str))

5. 多值参数

  1. def printnum(num, *nums, **numss):
  2. print(num)
  3. print(nums)
  4. print(numss)
  5. if __name__=='__main__':
  6. printnum(1,2,3,4,x=5)
  7. # 1
  8. # (2,3,4)
  9. # {'x':5}

#参考资料:

【1】黑马python教程

【2】廖雪峰python教程