【问题标题】:How to delete the first line of a text file?如何删除文本文件的第一行?
【发布时间】:2013-12-20 07:00:27
【问题描述】:

我一直在网上搜索,但没有找到任何好的解决方案。

这是我的文本文件:

[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]
[24, 28, 38, 37, 9, 44, -14, 84, -40, -92, 86, 94, 95, -62, 12, -36, -12]
[-26, -67, -89, -7, 12, -20, 76, 88, -15, 38, -89, -65, -53, -84, 31, -81, -91]
[-19, -50, 16, 47, -42, -31, 75, 0, 25, -95, 75, 97, 19, 77, -2, -31, -59]
[-66, -10, 35, -39, 24, 70, 74, -45, -27, 77, -44, 86, 57, 14, -91, -26, -20]
[-63, 80, -31, 70, 100, 22, -30, 74, 44, -35, -25, -75, -39, -13, -93, 0, 1]
[63, 13, 67, 55, -56, 45, 10, 61, -14, -55, 40, 84, -59, 7, 75, -64, -25]
[7, -50, -17, -86, -43, 34, 82, 84, 49, 18, 56, -31, -19, 59, -96, 72, -40]
[-73, 34, -68, 20, 30, 1, 49, 77, -94, 2, -83, 40, 2, 20, 66, 60, -36]
[-80, -12, 93, 77, 73, -55, 24, 3, -60, 12, -41, -43, -49, 36, 6, -93, -24]
[-41, 12, -43, 42, -70, 75, -84, -83, 30, 78, -3, 51, 69, 0, 65, 60, -15]
[82, 97, -57, -96, 25, -100, 61, 13, -80, -32, 99, 60, 58, -58, -45, -58, -53]
[-90, -34, 80, 95, -12, -34, 71, -83, 46, 10, -78, -40, 65, 53, -81, 40, -59]
[-80, -20, -87, -2, -54, 74, -79, 22, -20, 60, -84, -12, -40, -98, -81, -5, -35]
[33, 36, -46, 10, -77, 88, -99, -5, 19, -20, 89, 87, -47, 46, 10, 17, -67]
[-77, 73, 20, 44, 79, -14, -8, -49, 45, -49, -91, -21, 41, -13, 74, -71, -15]
[98, -99, 51, 53, 56, -78, 31, 45, 35, -36, -10, -86, 9, 94, 24, -2, -20]
[-37, 46, -77, -92, 48, -34, 75, 19, -74, -13, -100, 33, -46, 19, -60, 5, 5]
[-13, -30, -82, -70, 64, 87, 16, 67, -36, 22, -99, -92, 36, 8, 90, 48, -5]
[46, 75, -15, 24, 24, -37, -3, -45, 32, -84, -2, -16, 43, -88, 92, 27, -10]

我想要的只是删除第一行(这意味着使用第二行作为第一行,而不是用空格填充第一行)。

谁能帮帮我?

【问题讨论】:

  • 您不应该为此使用 python,而应该使用 bash 命令 sed -i -e "1d" $FILE
  • 也许 python 不是首选的武器。一个简单的tail -n +2 "$FILE" 就可以解决问题吗?
  • @Hyperboreus 如果用户想使用 Python,那就这样吧。在 Python 以及任何其他语言中都有快速的方法来做到这一点。
  • @F3AR3DLEGEND 当然可以。我只是想指出另一种方式,以防 OP 在 python 上过于固定(我不知道)。你知道:“如果你知道的唯一工具是锤子,那么所有问题都像钉子”。
  • @zaftcoAgeiha :它可能需要在 python 应用程序本身内完成,就像我的情况和我来这里的原因:)。我使用从 python 脚本在 shell 上调用的“sed 命令”做了同样的事情,但是我的代码审阅者不想为这样一个简单的事情生成一个新进程.....两者都有优点和缺点,就像在 file.read () 文件需要在内存中读取,对于大文件可能是个问题,但我需要先检查我的代码:)

标签: python file


【解决方案1】:

假设你有足够的内存来保存内存中的所有内容:

with open('file.txt', 'r') as fin:
    data = fin.read().splitlines(True)
with open('file.txt', 'w') as fout:
    fout.writelines(data[1:])

我们可以变得更有趣,打开文件,阅读,然后回到开头,消除第二个 open,但实际上,这可能已经足够了。

【讨论】:

  • head, tail = fin.read().split('\n', 1); ...; fout.write(tail) 可能效率更高。
  • @coldfix -- 是的,你可能是对的。虽然您可能大部分时间都花在 IO 上,所以这可能不会产生太多的不同。
  • 当您从更多线程中使用文件时,这是不安全的,或者其他东西也使用该文件。理论上,不删除第一行也可以阅读。再次运行后,您将得到相同的线路 - 处理金钱或重要数据时不安全。
  • 当然——如果你希望像这样使用线程来改变状态,它永远不会是线程安全的——这取决于你获得一个适当的锁来防止讨厌的竞争条件或其他什么。
【解决方案2】:

这是一个使用shutil的内存效率(?)解决方案:

import shutil

source_file = open('file.txt', 'r')
source_file.readline()
# this will truncate the file, so need to use a different file name:
target_file = open('file.txt.new', 'w')

shutil.copyfileobj(source_file, target_file)

【讨论】:

    【解决方案3】:

    您可以简单地说明要阅读的第一行是什么来更容易地做到这一点:

        with open(filename, "r") as f:
            rows = f.readlines()[1:]
    

    【讨论】:

      【解决方案4】:

      此解决方案适用于通过一次读取和写入一行而无法放入内存的大文件:

      import os
      from shutil import move
      from tempfile import NamedTemporaryFile
      
      # Take off the first line which has the system call and params
      file_path = 'xxxx'
      temp_path = None
      with open(file_path, 'r') as f_in:
          with NamedTemporaryFile(mode='w', delete=False) as f_out:
              temp_path = f_out.name
              next(f_in)  # skip first line
              for line in f_in:
                  f_out.write(line)
      
      os.remove(file_path)
      move(temp_path, file_path)
      

      【讨论】:

        【解决方案5】:

        如果您想使用来自另一个线程/进程的文件,使用一个 open 进行读写更安全:

        def pop(self, file):
            with open(file, 'r+') as f: # open file in read / write mode
                firstLine = f.readline() # read the first line and throw it out
                data = f.read() # read the rest
                f.seek(0) # set the cursor to the top of the file
                f.write(data) # write the data back
                f.truncate() # set the file size to the current size
                return firstLine
        
        fifo = pop('filename.txt')
        

        【讨论】:

          【解决方案6】:

          为此,Bash 会更快。你可以在你的 python 脚本中使用这些:

          subprocess.Popen.communicate()
          

          我为shell写了一个运行子进程cmd的函数:

          def popen_method(call):
              subprocess_call = Popen([call], shell=True, stdout=PIPE, stderr=PIPE)
              out, err = subprocess_call.communicate()
              if err:
                  raise yourError(
                      '\n============= WARNING/ERROR ===============\n{}\n===========================================\n'.format(
                          err.rstrip()))
              return out
          

          你这样称呼它:

          testing = "sed -i /var/output/ip_list.csv -e '1 s/^.*$/host_id,ip,last_updated/g'"
          popen_method(testing)
          

          或使用:

          from sh import sed
          

          然后运行 ​​sed 命令:

          sed -i /var/output/ip_list.csv -e '1 s/^.*$/host_id,ip,last_updated/g'
          

          这将用host_id,ip,last_updated 替换您在第一行的任何内容。

          【讨论】:

          • sed 的关键部分是:'1 s/^.*$/host_id,ip,last_updated/g' 其中 1 删除第一行(您也可以执行 sed "1d")和 s/ ^.$/wtv 这里将替换 /g 这将从 ^ 开始行到结束行 $ 替换为 "wtv here..." g=globally
          【解决方案7】:

          只是一个建议,因为我遇到了同样的问题,不同之处在于我不想从原始 .txt 文件中删除第一个原始文件,只是为了使用第二个原始文件中的内容。

          我用的是简单的解决方案

          with open(file) as f:
              content = f.readlines()
              content = content[1:]
          

          如果您不想永久删除文件的内容,总是会出现这种情况。

          【讨论】:

            【解决方案8】:

            我也想读取文件的第一行:

            # open the file and read the contents
            fp = open(file_path_name)
            content = fp.readline()                 # read just the first line
            print(content)
            

            对我来说效果很好。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2021-06-20
              • 1970-01-01
              • 2010-09-25
              • 2011-02-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多