Is it possible to modify lines in a file in-place?

前端 未结 5 1192
眼角桃花
眼角桃花 2020-11-22 08:29

Is it possible to parse a file line by line, and edit a line in-place while going through the lines?

5条回答
  •  自闭症患者
    2020-11-22 08:55

    fileinput module has very ugly API, I find beautiful module for this task - in_place, example for Python 3:

    import in_place
    
    with in_place.InPlace('data.txt') as file:
        for line in file:
            line = line.replace('test', 'testZ')
            file.write(line)
    

    main difference from fileinput:

    • Instead of hijacking sys.stdout, a new filehandle is returned for writing.
    • The filehandle supports all of the standard I/O methods, not just readline().

    Some useful notes from @rocksNwaves placed in comment

提交回复
热议问题