edit text file using Python

前端 未结 6 1320
忘了有多久
忘了有多久 2020-12-14 04:55

I need to update a text file whenever my IP address changes, and then run a few commands from the shell afterwards.

  1. Create variable LASTKNOWN = \"212.171.13

6条回答
  •  渐次进展
    2020-12-14 05:29

    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().

    for example - fileinput can line by line editing only, in_pace allow read whole file to memory (if it not big) and modify it.

提交回复
热议问题