文件

it2024-10-30  7

f=open('ly.txt','r',encoding='utf-8') # 文件句柄 'w'为创建文件,之前的数据就没了 data=f.read() print(data) f.close() f=open('test','a',encoding='utf-8') # 文件句柄 'a'为追加文件 append f.write("\n阿斯达所,\n天安门上太阳升") f.close() f = open('ly.txt', 'r', encoding='utf-8') # 文件句柄 for i in range(5): print(f.readline().strip()) # strip()去掉空格和回车 for line in f.readlines(): print(line.strip()) # 到第十行不打印 for index,line in enumerate(f.readlines()): if index==9: print('----我是分隔符-----') continue print(line.strip()) # 到第十行不打印 count=0 for line in f: if count==9: print('----我是分隔符-----') count += 1 continue print(line.strip()) count += 1 f = open('ly.txt', 'r', encoding='utf-8') # 文件句柄 print(f.tell()) print(f.readline(5)) print(f.tell()) f.seek(0) print(f.readline(5)) print(f.encoding) print(f.buffer) print(f.fileno()) print(f.flush()) # 刷新缓冲区 # 进度条 import sys,time for i in range(50): sys.stdout.write('#') sys.stdout.flush() time.sleep(0.5) f = open('ly.txt', 'a', encoding='utf-8') # 文件句柄 f.seek(10) f.truncate(20) # 指定10到20个字符,10个字符前面留着,后面20字符清除 f = open('ly.txt', 'r+', encoding='utf-8') # 文件句柄 print(f.readline().strip()) print(f.readline().strip()) print(f.readline().strip()) f.write("我爱中华") f.close() # 实现简单的shell sed替换功能 f=open("ly.txt","r",encoding="utf-8") f_new=open("ly2.txt","w",encoding="utf-8") for line in f: if "肆意的快乐" in line: line=line.replace("肆意的快乐","肆意的happy") f_new.write(line) f.close() f_new.close() import sys f=open("ly.txt","r",encoding="utf-8") f_new=open("ly2.txt","w",encoding="utf-8") find_str = sys.argv[1] replace_str = sys.argv[2] for line in f: if find_str in line: line=line.replace(find_str,replace_str) f_new.write(line) f.close() f_new.close() # with语句---为了避免打开文件后忘记关闭,可以通过管理上下文 with open('ly.txt','r',encoding='utf-8') as f: for line in f: print(line.strip()) # python2.7后,with又支持同时对多个文件的上下文进行管理,即: with open('ly.txt','r',encoding='utf-8') as f1,open('ly2.txt','r',encoding='utf-8'): pass

output: 0

0

utf-8 <_io.BufferedReader name=‘ly.txt’> 4 None ##################################################

我爱中华

最新回复(0)