Python: Open a file, search then append, if not exist

后端 未结 2 2251
眼角桃花
眼角桃花 2021-02-19 01:56

I am trying to append a string to a file, if the string doesn\'t exit in the file. However, opening a file with a+ option doesn\'t allow me to do at once, because o

2条回答
  •  甜味超标
    2021-02-19 02:42

    You can set the current position of the file object using file.seek(). To jump to the beginning of a file, use

    f.seek(0, os.SEEK_SET)
    

    To jump to a file's end, use

    f.seek(0, os.SEEK_END)
    

    In your case, to check if a file contains something, and then maybe append append to the file, I'd do something like this:

    import os
    
    with open("file.txt", "r+") as f:
        line_found = any("foo" in line for line in f)
        if not line_found:
            f.seek(0, os.SEEK_END)
            f.write("yay, a new line!\n")
    

提交回复
热议问题