首页 > 解决方案 > 使用可以从命令行运行的 Python 脚本将指定数量的行复制到多个文档

问题描述

我正在尝试构建一个脚本,将指定数量的行从一个文档复制到多个其他文档。复制的行应该附加到文档的末尾。如果我想从文档末尾删除行,脚本还必须能够删除指定数量的行。

我希望能够从命令行运行脚本并希望传递两个参数:

  1. “添加”或“删除”
  2. 行数(从文档末尾开始计算) 命令可能如下所示: py doccopy.py add 2将最后 2 行复制到其他文档,或者: py doccopy.py del 4从所有文档中删除最后 4 行。

到目前为止,我已经编写了一个函数,可以从原始文档中复制我想要的行数,

def copy_last_lines(number_of_lines):
    line_offset = [0]
    offset = 0
    for line in file_to_copy_from:
        line_offset.append(offset)
        offset += len(line)
    file_to_copy_from.seek(line_offset[number_of_lines])
    changedlines = file_to_copy_from.read()

将所述行粘贴到文档的函数

def add_to_file():
    doc = open(files_to_write[file_number], "a")
    doc.write("\n")
    doc.write(changedlines.strip())
    doc.close()

和一个主要功能:

def main(action, number_of_lines):
    if action == "add":
        for files in files_to_write:
            add_to_file()
    elif action == "del":
        for files in files_to_write:
            del_from_file()
    else:
        print("Not a valid action.")

主要功能还没有完成,当然我还没有弄清楚如何实现del_from_file函数。我也有循环浏览所有文档的问题。

我的想法是创建一个列表,包括我要写入的文档的所有路径,然后循环遍历该列表并为“原始”文档创建一个变量,但我不知道这是否可能我要做。如果可能的话,也许有人知道如何使用单个列表来实现所有这些,将“原始”文档作为第一个条目,并在写入其他文档时循环以“1”开头的列表。

我意识到到目前为止我所做的代码完全是一团糟,我问了很多问题,所以我会很感激每一点帮助。我对编程完全陌生,过去 3 天我刚刚参加了 Python 速成课程,我自己的第一个项目比我想象的要复杂得多。

标签: pythonpython-3.xcommand-line

解决方案


我认为这应该满足您的要求。

# ./doccopy.py add src N dst...
#    Appends the last N lines of src to all of the dst files.
# ./doccopy.py del N dst...
#    Removes the last N lines from all of the dst files.

import sys

def process_add(args):
    # Fetch the last N lines of src.
    src = argv[0]
    count = int(args[1])
    lines = open(src).readlines()[-count:]

    # Copy to dst list.
    for dst in args[2:}
        open(dst,'a').write(''.join(lines))

def process_del(args):
    # Delete the last N lines of each dst file.
    count = int(args[0])
    for dst in args[1:]:
        lines = open(dst).readlines()[:-count]
        open(dst,'w').write(''.join(lines))

def main():
    if sys.argv[1] == 'add':
        process_add( sys.argv[2:] )
    elif sys.argv[1] == 'del':
        process delete( sys.argv[2:] )
    else:
        print( "What?" )

if __name__ == "__main__":
    main()

推荐阅读