How to delete the first line of a text file?

前端 未结 8 2041
醉梦人生
醉梦人生 2020-11-29 09:10

I have been searching online, but have not found any good solution.

Here is my text file:

[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3,          


        
8条回答
  •  半阙折子戏
    2020-11-29 09:33

    This solution will work for big files that don't fit into memory by reading and writing one line at a time:

    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)
    

提交回复
热议问题