Advanced Applications 040 files

Both editing mode file

  • Data files are stored on the hard disk, so there is only covering, say there is no modification
  • Modify the contents of the file can be understood as the fact that we open the original file to read the file, write way to open another new file. The contents of the original file to be modified, and then written to the new file, and then use the os module methods, to delete the original file, the new file is renamed to the original file name

1. Direct modification disposable

  • Disposable modify the file contents involves deleting files and modifying the file name, this time we can import os a library, a library inside the os and rename method remove method
import os
with open('test.py', 'r', encoding='utf8') as fr, \
        open('test_swap.py', 'w', encoding='utf8') as fw:
    data = fr.read()
    data = data.replace('sb', 'sb')

    fw.write(data)

import time
time.sleep(5)
os.remove('test.py')  # 删除文件
os.rename('test_swap.py', 'test.py')  # 重命名文件

2. Modify line by line

import os
with open('test.py', 'r', encoding='utf8') as fr ,\
        open('test.txt', 'w', encoding='utf8') as fw:
    for data in fr:
        data = data.replace('sb', 'dsb')

        fw.write(data)

os.remove('test.py')# 删除文件
os.rename('test.txt','test.py')# 重命名文件

Guess you like

Origin www.cnblogs.com/xichenHome/p/11323349.html