Python Notes (8)

来源:互联网 发布:淘宝客有要交钱的 编辑:程序博客网 时间:2024/06/06 01:12

转载请注明出处:http://blog.csdn.net/cxsydjn/article/details/71303892

The note covers how to apply what just learned to a real-world application: writing data to a file.

Python notes of open courses @Codecademy.

File I/O (Input/Output)

  • f = open("output.txt", "w")
    • This told Python to open output.txt in "w" mode (“w” stands for “write”).
    • It stored the result of this operation in a file object, f.
  • Four modes
    • "w": write-only mode
    • "r": read-only mode
    • "r+": read and write mode
    • "a": append mode, which adds any new data you write to the file to the end of the file.
  • .write(): writes to a file.
    • It takes a string argument. str() might be used.
  • .read(): reads from a file.
  • .close(): You must close the file after writing.

Advanced Functions

  • .readline(): reading between the lines
    • If you open a file and call .readline() on the file object, you’ll get the first line of the file; subsequent calls to .readline() will return successive lines.
  • Buffering Data
    • During the I/O process, data is buffered: this means that it is held in a temporary location before being written to the file.
    • Python doesn’t flush the buffer.
    • If we don’t close a file, our data will get stuck in the buffer.
  • with and as

    • A way to get Python to automatically close files.
    • File objects contain a special pair of built-in methods: __enter__() and __exit__(). When a file object’s __exit__() method is invoked, it automatically closes the file.
    • Using with and as to invoke the __exit__() method, the syntax looks like this:

      with open("file", "mode") as variable:    # Read or write to the file
  • .closed
    • Python file objects have a closed attribute which is True when the file is closed and False otherwise.
    • By checking file_object.closed, we’ll know whether our file is closed and can call close() on it if it’s still open.

External Resources

  • Python Files I/O
0 0
原创粉丝点击