周六上午在家闲着,老婆在睡觉,小孩陪大姨出去玩了。
我就 进电脑房,拿起《PYTHON基础教程》,按书写起样例代码。
看到二百多页,讲到文件操作了。
文件操作在IT工作中很有用的。因为很多工作都是从配置文件里读取每一行参数,然后,对每一个进行同样的设置操作。
1 #file_operation.py 2 3 import fileinput,sys 4 5 filename = r'C:\python33\sample.txt' 6 7 def process(string): 8 print ('process:', string) 9 10 #operation very char string 11 f = open(filename) 12 while True: 13 char = f.read(1) 14 if not char: break 15 process(char) 16 f.close() 17 18 #operation very line 19 f = open(filename) 20 while True: 21 line = f.readline() 22 if not line: break 23 process(line) 24 f.close() 25 26 #operation with for operate 27 f = open(filename) 28 for char in f.read(): 29 process(char) 30 f.close() 31 32 f = open(filename) 33 for line in f.readlines(): 34 process(line) 35 f.close() 36 37 #operation fileimput model 38 for line in fileinput.input(filename): 39 process(line) 40 f.close() 41 42 #operation fileimput model 43 f = open(filename) 44 for line in f: 45 process(line) 46 f.close() 47 #more less 48 for line in open(filename): 49 process(line) 50 51 #demo sys.stdin 52 for line in sys.stdin: 53 process(line)
时间: 2024-09-21 06:14:09