【问题标题】:Remove lines from beginning and end of file and write remaining lines to new file从文件的开头和结尾删除行并将剩余的行写入新文件
【发布时间】:2018-04-29 22:19:19
【问题描述】:

我正在尝试创建一个函数来从一个文件中复制行,从文件中删除第一行 omit_from_start 和最后一个 omit_from_end 行,并将其余行写入新文件。

这是我尝试过的:

def truncate_file(file1, file2):
#    file1 = "omit_lines_test.txt"    # Just for testing
#    file2 = "truncated_file.txt"    # Just for testing
    infile = open(file1, "r")
    outfile = open(file2, "w")

    print("\n*** Truncating file copy ***\n")
    omit_from_start = int(input("Omit how many lines from the start: "))
    omit_from_end = int(input("Omit how many lines from the end: "))

    lines_to_output = []

    lines = [line for line in infile]
    lines_to_output.append(str(lines[omit_from_start:omit_from_end]))

    for line in lines_to_output:
        for character in line:
            outfile.write(character)

    infile.close()
    outfile.close()

我的infile 只是一个包含['1\n', '2\n', '3\n', '4\n', '5\n', '6\n', '7\n', '8\n', '9\n', '10\n'] 的文本文件,我需要outfile 包含例如['4\n', '5\n', '6\n', '7\n', '8\n'] 用于omit_from_start = 3omit_from_end = 2

目前,lines_to_output 仅包含 ['[]']。我也尝试过使用 .join() 和 .pop() 方法,但它们也不会产生我想要的结果。

【问题讨论】:

  • @eyllanesc:您链接到的问题是关于搜索每一行以查找特定字符串的问题。我只是想省略行的范围。如您所见,我尝试对lines 列表进行切片。
  • 您可能想要lines[omit_from_start:-omit_from_end]lines[omit_from_start:len(line)-omit_from_end](取决于您想要为0 做什么)。
  • 另外,由于您通过将整个文件读入行列表并将行列表输出到另一个文件来执行此操作,因此文件部分不相关 - 关于如何从 list 的开头和结尾删除元素会对您有所帮助。这是一个更容易的问题(你已经写了困难的部分)。

标签: python python-3.x list file


【解决方案1】:

这种方法确实对 infile 进行了额外的扫描以查找行数,但它确实具有在复制期间不必将整个 infile 保留在内存中的好处。因此,它可能比处理较小文件的原始方法慢,但允许该方法处理非常大的文件。

def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1

def truncate_file(file1, file2):
    infile = open(file1, "r")
    outfile = open(file2, "w")

    print("\n*** Truncating file copy ***\n")
    omit_from_start = int(input("Omit how many lines from the start: "))
    omit_from_end = int(input("Omit how many lines from the end: "))

    length = file_length(file1)

    # This iteration prevents whole file being stored in memory
    for i, line in enumerate(infile):
        if i < omit_from_start:
            continue;
        elif i < length - omit_from_end:
            outfile.write(line)
        elif
           break

    infile.close()
    outfile.close()

实际上并没有运行代码,所以可能是一些边界错误,但方法是扫描 infile 的文件长度,然后再次迭代 inline 文件,省略起始行,然后在以下情况下中断迭代达到长度 - omit_from_end 字符串。

没有进行任何输入验证来确认 omit_from_start 介于零和小于长度减去 omit_from_end 或 omit_from_end 小于长度 - omit_from_start 之间

【讨论】:

    猜你喜欢
    • 2020-11-22
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多