python(文件中指定行中插入一行内容)

难点分析


(1)读取文件报错

UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 279: illegal multibyte sequence

检查文件中是否含有中文字符,如有,将代码为encoding=‘utf-8’

(2)插入一行的思路其实比较简单、暴力:将源文件中的每一行保留在一个list中,然后在list中插入一行,再写回源文件。
(3)Python命令参数:

: python xx.py argv[0] argv[1] ...
# 切记要先判断len(sys.argv)参数的个数是否达到预期,边界的判断和处理一定要全面,否则就可能会crash
sys.argv[0]  # 获取第一个参数
sys.argv[1]  # 获取第二个参数

代码


import sys
import os


def writeinfile(path, cont, line=0):
    lines = []
    with open(path, 'r', encoding='utf-8') as r:
        for l in r:
            lines.append(l)
    if line == 0:
        lines.insert(0, '{}\n'.format(cont))
    else:
        lines.insert(line-1, '{}\n'.format(cont))
    s = ''.join(lines)
    # print(s)
    with open(path, 'w') as m:
        m.write(s)
        print('writeInFile Success!')


def workit(dir_path, content):
    dirpath = dir_path
    filelists = [x for x in os.listdir(dirpath) if x.endswith('.py')]

    if filelists and len(filelists) > 0:
        print('filelist is %s' % filelists)
        filepaths = list(map(lambda x: os.path.join(dirpath, x), filelists))
        for f in filepaths:
            writeinfile(f, content, 5)
    else:
        print('nothing to handle!')

if __name__ == '__main__':
    # print('len is %s' % len(sys.argv))
    if len(sys.argv) == 3:
        workit(sys.argv[1], sys.argv[2])
    else:
        if len(sys.argv) == 2:
            workit(sys.argv[1], '#!/usr/bin/env python3')
        else:
            print("-" * 5, "Please Input the right Arguments!\ne.g. Python [xx.py] [filePath] [content]!", "-" * 20)
            raise KeyboardInterrupt



最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容