>>> f = open('test','a+') # Not using 'with' just to simplify the example REPL session>>> f.write('hi')>>> f.seek(0)>>> f.read()'hi'>>> f.seek(0)>>> f.write('bye') # Will still append despite the seek(0)!>>> f.seek(0)>>> f.read()'hibye'
Mode Description
'r' This is the default mode. It Opens file for reading.'w' This Mode Opens file for writing.If file does not exist, it creates a new file.If file exists it truncates the file.'x' Creates a new file. If file already exists, the operation fails.'a' Open file in append mode.If file does not exist, it creates a new file.'t' This is the default mode. It opens in text mode.'b' This opens in binary mode.'+' This will open a file for reading and writing (updating)
Example does not work well with multiple processes:
f = open("logfile", "w"); f.seek(0, os.SEEK_END); f.write("data to write");
writer1: seek to end of file. position 1000 (for example)writer2: seek to end of file. position 1000writer2: write data at position 1000 end of file is now 1000 + length of data.writer1: write data at position 1000 writer1's data overwrites writer2's data.
通过使用追加模式,操作系统将在文件末尾放置任何写入。
f = open("logfile", "a"); f.seek(0, os.SEEK_END); f.write("data to write");