1 # 文件的操作 2 3 4 ''' 5 # 以只读模式打开 6 import sys, time 7 f = open('lyrics.txt', 'r') 8 9 print(f.read()) # 读取整个文件10 print(f.readline()) # 读取文件中的一行11 print(f.readlines()) # 将整个文件的所有行读出12 for i in range(5):13 print(f.readline()) # 读取指定行数14 for line in f.readlines(): # 将整个文件的所有行读出15 print(line.strip())16 17 for index, line in enumerate(f.readlines()): # 枚举18 print(line.strip())19 if index == 10: # 在第十行之后打印20 print('---------------------------------')21 22 for index, line in enumerate(f.readlines()): # 枚举23 if index == 10: # 在第十行之后打印24 print('---------------------------------')25 continue26 print(line.strip())27 28 # 以读写模式打开,可追加内容29 f = open('lyrics.txt', 'r+')30 print(f.readline())31 f.write('\n1989-1989-1989-1989-1989-1989')32 print(f.readlines())33 34 # 以只写模式打开35 f = open("lyrics.txt", 'w')36 f.write('Written by Taylor Swift')37 print(f.truncate(20)) # 从头开始截断20个字符之后的内容38 39 # 追加内容40 f = open('lyrics.txt', 'a')41 f.write('\nWritten by Taylor Swift')42 43 # 追加读模式44 f = open('lyrics.txt', 'a+')45 print(f.readlines())46 f.write('\nBigMachine 2017')47 48 49 print(f.tell()) # 返回指针位置50 print(f.readline())51 print(f.readline())52 print(f.readline())53 print(f.tell())54 55 print(f.seekable())56 f.seek(100) # 设置指针位置57 print(f.readline())58 print(f.readline())59 print(f.readline())60 61 print(f.encoding) # 返回编译器62 print(f.fileno()) # 返回文件编号63 print(f.name) # 返回文件名64 print(f.flush()) # 将缓存强制写入硬盘65 66 # 进度条67 for i in range(100):68 sys.stdout.write('#')69 sys.stdout.flush()70 time.sleep(0.1)71 72 # 打开二进制文件73 f = open('lyrics.txt', 'rb')74 print(f.readlines())75 76 # 写入二进制文件77 f = open('lyrics.txt', 'wb')78 f.write('19891989198919819189189'.encode())79 80 # 文件修改81 f = open('lyrics.txt', 'r')82 fnew = open('lyrics.bak','w') # 写出一个新文件83 84 for line in f:85 if 'Oh no' in line:86 line = line.replace('Oh no', 'Oh yes')87 fnew.write(line)88 fnew.close()89 90 # 能够自动关闭文件的方法(避免占用过多内存)91 with open('lyrics.txt', 'r') as f:92 print(f.readlines())93 '''94 95 96 # f.close() # 关闭文件97 98 print(f.closed) # 判断是否已经关闭