代码之家  ›  专栏  ›  技术社区  ›  Hadsga

从txt文件中删除前n行

r
  •  0
  • Hadsga  · 技术社区  · 1 年前

    我有这个txt文件:

    c("\\f0\\fs24 \\cf0 <message messageId=\"12450\" replyToMessageId=\"0\" receivedAt=\"2023-06-12T08:42:31Z\" text=\"&gt; GBPJPY SELL 175.41&#xA;&#xA;SL:  175.955&#xA;TP:  174.382&#xA;--Trade by Grace\" />\\", 
    "", "  <message messageId=\"12448\" replyToMessageId=\"12442\" receivedAt=\"2023-06-12T02:38:51Z\" text=\"&gt; SET SL TO 1.32979\" />\\", 
    "  <message messageId=\"12447\" replyToMessageId=\"12442\" receivedAt=\"2023-06-12T02:38:51Z\" text=\"&gt; USDCAD CLOSE HALF 33  PIPS PROFIT \" />\\", 
    "  <message messageId=\"12446\" replyToMessageId=\"12430\" receivedAt=\"2023-06-12T00:42:27Z\" text=\"&gt; EURAUD RUNNING 105+ PIPS PROFIT &#xA;SMALL LOT HOLDER CAN FULL CLOSE WITH PROFIT \" />\\", 
    "  <message messageId=\"12442\" replyToMessageId=\"0\" receivedAt=\"2023-06-09T14:42:21Z\" text=\"&gt; USDCAD BUY 1.3328&#xA;&#xA;SL:  1.31655&#xA;TP:  1.34473&#xA;--Trade by Jason\" />\\", 
    "  <message messageId=\"12441\" replyToMessageId=\"12430\" receivedAt=\"2023-06-09T14:25:46Z\" text=\"&gt; EURAUD CLOSE PARTIAL 69  PIPS PROFIT  MOVE SL TO ENTRY\" />\\", 
    "  <message messageId=\"12440\" replyToMessageId=\"12436\" receivedAt=\"2023-06-09T12:33:37Z\" text=\"&gt; SET SL TO 175.401\" />\\", 
    "  <message messageId=\"12439\" replyToMessageId=\"12436\" receivedAt=\"2023-06-09T12:33:36Z\" text=\"&gt; GBPJPY CLOSE HALF 34  PIPS PROFIT \" />\\", 
    "  <message messageId=\"12438\" replyToMessageId=\"12430\" receivedAt=\"2023-06-09T12:32:57Z\" text=\"&gt; SET SL TO 1.60599\" />\\"
    )
    

    如何在不重新读取文件的情况下删除前5行?

    1 回复  |  直到 1 年前
        1
  •  2
  •   Jannik Sinz    1 年前

    在不读取文件的情况下,不能删除文件中的行。但是,可以用减去前5行的内容覆盖文件。以下是如何在Python中执行此操作:

    with open('yourfile.txt', 'r') as file:
        lines = file.readlines()
    
    with open('yourfile.txt', 'w') as file:
        file.writelines(lines[5:])
    

    在R中,可以使用readLines函数将文件读取到向量中,然后使用writeLines函数把修改后的向量写回文件。以下是您的操作方法:

    lines <- readLines("yourfile.txt")
    writeLines(lines[-(1:5)], "yourfile.txt")
    
        2
  •  1
  •   TarJae    1 年前

    我们可以简单地做:

    text_data <- text_data[-(1:5)]
    

    此方法将删除第1-5行。如果数据已经存储在变量中,则无需重新加载它。