# -*- coding: UTF-8 -*- file_full = '/Users/xc/git-python/day5/test.txt' enter = '\n' ###============读文件============### # with open(file_full , 'r') as f: # line = f.readline() # print(line) # f.seek(0) #文件内部光标位置指定 ###============写文件============### # with open(file_full , 'w', encoding='utf-8') as f: # (w) 写模式 # f.write(f'hello{enter}') # f.write(f'hello{enter}') ###============文件内容追加============### # with open(file_full , 'a', encoding='utf-8') as f: # (a) 增加模式 # f.write(f'hello{enter}') # f.write(f'hello{enter}') ###============文件拷贝与内容替换============### wf = file_full.replace('test.txt', 'test.txt.swap') # 拷贝文件,(1 ,2) 1是原文件,2是修改后的文件名 with open( file_full, 'r', encoding='utf-8') as rf_obj, open( wf, 'w',encoding='utf-8') as wf_obj: # 括号中可以换行,不影响 for line in rf_obj: ll = line.replace('hello', 'word') #字符串替换,如果 (1,2)不存在,返回原来的值。2为替换后的值 wf_obj.write(ll) import os os.remove(file_full) os.rename(wf,file_full) # 上面代码与 vim 编辑器功能类似