change first line of a file in python

前端 未结 7 2109
不思量自难忘°
不思量自难忘° 2020-12-02 19:05

I only need to read the first line of a huge file and change it.

Is there a trick to only change the first line of a file and save it as another file using Python? A

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 19:18

    An alternate solution that does not require iterating over the lines that are not of interest.

    def replace_first_line( src_filename, target_filename, replacement_line):
        f = open(src_filename)
        first_line, remainder = f.readline(), f.read()
        t = open(target_filename,"w")
        t.write(replacement_line + "\n")
        t.write(remainder)
        t.close()
    

提交回复
热议问题