Python Notes (8) - File Input/Output

转载请注明出处: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值