for循环
1 2 3 4 5
| for i in range(5): print(i) i += 1
1 2 3 4 5
|
for 循环中的 循环变量 不会被修改,此时应使用 while。
with表达式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| with open('output/0.txt') as f1: f2 = open('output/2.txt') print(f2.readline()) print(f1.readline())
2016-03-22 20:25:28,20001,89,NQ,396,58.00,S Traceback (most recent call last): File "D:/0hadoop/python/pystudy/action/test.py", line 7, in <module>
print(f1.readline()) ValueError: I/O operation on closed file.
|
with表达式建立的上下文会自动关闭IO。
列表
%
1 2
| System.out.println(-123%10)
|
Python IO
读text data
1 2 3 4 5 6 7
| with open('somefile.txt') as f: data=f.read()
with open('somefile.txt') as f: for line in f:
|
写text data,会覆盖。
1 2 3 4 5 6 7 8
| with open('somefile.txt') as f: f.write(text1) f.write(text2) with open('somefile.txt') as f: print(line1,file=f) print(line2,file=f)
|
追加文本文件,open(… , ‘at’)
binary data
such as images、sound files等等。
Infinite
如果只需要一个表示无限的数,可以用:
1 2
| float('inf') float('-inf')
|
全局变量不要命名太简单,例如 i,j;否则容易与局部变量冲突。