本文共 2830 字,大约阅读时间需要 9 分钟。
2.6 使用for循环遍历文件
2.7 使用while循环遍历文件
## Win系统下打开文件print(open(r'D:\111.txt'))#####################################f = open(r'D:\1111.txt', 'w') # 以w方式打开,没有则会创建f.write('sss') # 写入(覆盖)的内容;只接受字符串f.close() # 关闭打开的文件;不关闭则会占用内存####################################### 读文件内容f=open(r'D:\1111.txt','r').read()print(f)f.close() #####################################f=open(r'D:\1111.txt','r').read(5) # 读取5个字符print(f)f.close() #####################################f=open(r'D:\1111.txt','r').readline() # 以行来读内容print(f)f.close() #####################################f=open(r'D:\1111.txt','r').readlines() # 读取多行,返回listprint(f)f.close() ####################################### 逐行遍历f=open(r'D:\1111.txt').readlines()for i in f:print("{}".format(i),end="")f.close() ####################################### 直接遍历;对内存开销小f=open(r'D:\1111.txt')for i in f:print("{}".format(i),end="")f.close()
## 遍历文件f = open(r'D:\1111.txt')while 1: line = f.readline() if not line: break print(line)f.close()############################################ 遍历文件with open(r'D:\1111.txt') as f: # with open 会自动关闭文件 while 1: line = f.readline() if not line: break print(line)
l1 = []l2 = []with open(r'D:\test.txt') as f:while 1: line = f.readline() if line: for i in line: if i.isdigit(): l1.append(i) elif i != '\n': l2.append(i) else: breakl1.sort()l2.sort()with open(r'D:\test.txt','w') as f:for i in l1: f.write(i)else: f.write('\n')for i in l2: f.write(i)print("操作文成!")
import strings = 2dict1 = {'a': 97, 'c': 99, 'b': 98, 'e': 101, 'd': 100, 'g': 103, 'f': 102, 'i': 105, 'h': 104, 'k': 107, 'j': 106, 'm': 109, 'l': 108, 'o': 96, 'n': 110, 'q': 113, 'p': 112, 's': 115, 'r': 114, 'u': 117, 't': 116, 'w': 119, 'v': 118, 'y': 121, 'x': 120, 'z': 122}dict1['o'] = 111dict1 = sorted(dict1.items(), key=lambda a:a[0])dict1 = dict(dict1)dict2 = dict(zip(string.ascii_uppercase,range(65,92)))dict3 = dict(dict1, **dict2)dict3 = sorted(dict3.items(), key=lambda a:a[0])
with open(r'D:\dict.txt','w') as f:
for k,v in dict3:f.write(k + ' ')f.write(str(v) + '\n')转载于:https://blog.51cto.com/13542406/2055655