python知识框架
- 常量,变量,运算符,分支和循环
- 数据结构,函数
- 文件
- 模块,包
- 类
1. 文件:打开,读写,关闭
1.1. 文件对象:class '_io.TextIOWrapper'
1.2. 文件方法:
open("file_name")- r:只读,文件指针在开头
- w:覆盖,只写,文件指针在开头
- a:不覆盖,只写,文件指针在结尾
- r+/w+/a+:以读写方式打开(频繁移动文件指针会降低读写效率,因此很少使用该属性)
file.read()
while True:
txt_line = file.readline()
print(txt_line)
if not txt_line:
break
file.close()
-`file.write()`-`file.close()`> 实战案例:文件复制> ```python#--------------小文件读写------------------## 1.打开文件rfile = open("hello")wfile = open("empty_file","w")# 2.读hello.txt,写到empty_file.txtmessage = rfile.read()wfile.write(message)# 3.关闭文件rfile.close()wfile.close()#----------------大文件读写----------------## 1.打开文件rfile = open("hello")wfile = open("empty_file","w")# 2.读hello 写到empty_filewhile True:message = rfile.readline()wfile.write(message)if not message:break# 3.关闭文件rfile.close()wfile.close()
1.3. 标准打开读写关闭:with ... as ...:
- with … as …自动关闭文件
with open('/path/to/file', 'r') as f:print(f.read())'''try:f = open('/path/to/file', 'r')print(f.read())finally:if f:f.close()'''
with open('/Users/michael/test.txt', 'w') as f:f.write('Hello, world!')'''f = open('/Users/michael/test.txt', 'w')f.write('Hello, world!')f.close()'''
补充:
1. print:格式化输出%
user = "Charli"age = 8# 格式化字符串有两个占位符,第三部分提供2个变量print("%s is a %s years old boy" % (user , age))
2. function:def
def functionname( parameters ):"函数_文档字符串"function_suitereturn [expression]
3. class:class ClassName:
class Employee:def displayCount(self):print "Total Employee %d" % Employee.empCount
4. eval()函数:evaluate—-IDE中实现交互
案例实战:小型计算器
input_str = input("please enter a expression: ")print(eval(input_str))
5. 多值参数
def printnum(num, *nums, **numss):print(num)print(nums)print(numss)if __name__=='__main__':printnum(1,2,3,4,x=5)# 1# (2,3,4)# {'x':5}
#参考资料:
【1】黑马python教程
【2】廖雪峰python教程
