Files modified in two ways

Files modified in two ways

Data files are stored on the hard disk, so there is only covering, there is no modification is to say, we usually see modify the file, all simulated results, specifically implemented in two ways.

First, the way a

The contents of the file stored in the hard disk all loaded into memory, can be modified in memory after the modification is completed, and then covered by the memory to the hard disk (word, vim, nodpad ++ editor, etc.).

import os

with open('37r.txt') as fr, \
        open('37r_swap.txt', 'w') as fw:
    data = fr.read()  # 全部读入内存,如果文件很大,会很卡
    data = data.replace('tank', 'tankSB')  # 在内存中完成修改

    fw.write(data)  # 新文件一次性写入原文件内容

# 删除原文件
os.remove('37r.txt')
# 重命名新文件名为原文件名
os.rename('37r_swap.txt', '37r.txt')
print('done...')
done...

Second, the second approach

Contents of the file stored in the hard disk into memory line by line, the modification is completed on the new file is written, and finally cover the source file with a new file.

import os

with open('37r.txt') as fr,\
        open('37r_swap.txt', 'w') as fw:
    # 循环读取文件内容,逐行修改
    for line in fr:
        line = line.replace('jason', 'jasonSB')
        # 新文件写入原文件修改后内容
        fw.write(line)

os.remove('37r.txt')
os.rename('37r_swap.txt', '37r.txt')
print('done...')
done...

All in all, modify the contents of the file ideas for: to open the original file read, write way to open a 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, the original file delete, rename the new file to the original file name, to achieve the purpose of real ones.

Guess you like

Origin www.cnblogs.com/Dr-wei/p/11871562.html