使用可以从命令行运行的Python脚本将指定行数复制到多个文档中



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

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

  1. "添加";或";del">
  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速成班,我自己的第一个项目比我想象的要复杂得多。

我认为这应该按照你的要求进行。

# ./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()

最新更新