如何完全删除文本文件的第一行?

问题描述 投票:0回答:2

我有一个输出文本文件(Mod_From_SCRSTXT.txt)的脚本。我需要删除该文件的第一行。

我尝试更改下面显示的find函数的最后一行。即使更改,第一行仍会打印在创建的新文件中。

    def find(substr, infile, outfile):                        
      with open(infile) as a, open(outfile, 'a') as b:        
       for line in a:                                         
        if substr in line:                                    
         b.write(line[1:]) 

    srcn_path1 = input("   Enter Path. Example: U:\...\...\SRCNx\SCRS.TXT\n" +
                       "   Enter SRCS.TXT's Path: ")
    print ()

    scrNumber1 = input('   Enter SCR number: ')
    print ()

    def find(substr, infile, outfile):                        
      with open(infile) as a, open(outfile, 'a') as b:        
       for line in a:                                         
        if substr in line:                                    
         b.write(line) # or (line + '\n')                                

    # action station:                                          
    find(scrNumber1, srcn_path1, 'Mod_From_SCRSTXT.txt')

实际结果:

VSOAU-0004 16999  
VSOAU-0004
VSOAU-0004
VSOAU-0004
VSOAU-0004

预期结果:

VSOAU-0004
VSOAU-0004
VSOAU-0004
VSOAU-0004
python
2个回答
0
投票

您需要进行一些小的调整:

您可以计算文件中的行数:

numberOfLines = 0

for line in file:
    numberOfLines += 1

for line in range(1, linesInFile + 1):

或者您可以通过许多不同的方式忽略第一行,这很简单:

ignoredLine = 0

for line in file:
    if not ignoredLine:
        ignoredLine = 1
    else:
        #Do stuff with the other lines

0
投票
import pathlib
import os
import copy
import io

def delete_first_line(read_path):
    try:
        read_path = pathlib.Path(str(read_path))
        write_path = str(copy.copy(read_path)) + ".temp"
        while os.path.exists(write_path):
            write_path = write_path + ".temp"
        with open(read_path , mode = "r") as inf:
            with open(write_path, mode="w") as outf:
                it_inf = iter(inf)
                next(it_inf) # discard first line
                for line in it_inf:
                    print(line, file = outf)
        os.remove(read_path)
        os.rename(write_path, read_path)
    except StopIteration:
        with io.StringIO() as string_stream:
            print(
                "Cannot remove first line from an empty file",
                read_path,
                file = string_stream,
                sep = "\n"
            )
            msg = string_stream.getvalue()
        raise ValueError(msg)
    except FileNotFoundError:
        with io.StringIO() as string_stream:
            print(
                "Cannot remove first line from non-existant file",
                read_path,
                file = string_stream,
                sep = "\n"
            )
            msg = string_stream.getvalue()
        raise ValueError(msg)
    finally:
        pass
    return
© www.soinside.com 2019 - 2024. All rights reserved.