eout
发布于

python open read file

In Python, there are six methods or access modes, which are:

  • Read Only ('r’): This mode opens the text files for reading only. The start of the file is where the handle is located. It raises the I/O error if the file does not exist. This is the default mode for opening files as well.
  • Read and Write ('r+’): This method opens the file for both reading and writing. The start of the file is where the handle is located. If the file does not exist, an I/O error gets raised.
  • Write Only ('w’): This mode opens the file for writing only. The data in existing files are modified and overwritten. The start of the file is where the handle is located. If the file does not already exist in the folder, a new one gets created.
  • Write and Read ('w+’): This mode opens the file for both reading and writing. The text is overwritten and deleted from an existing file. The start of the file is where the handle is located.
  • Append Only ('a’): This mode allows the file to be opened for writing. If the file doesn't yet exist, a new one gets created. The handle is set at the end of the file. The newly written data will be added at the end, following the previously written data.
  • Append and Read (‘a+’): Using this method, you can read and write in the file. If the file doesn't already exist, one gets created. The handle is set at the end of the file. The newly written text will be added at the end, following the previously written data.
 with open(f"info-{host}.log", "w+") as f:
        // write something. want to read out 
        f.seek(0) # 把指针归0
        print(f.read())

浏览 (1615)
点赞
收藏
评论