file types:

  • plaintext files, such as .txt .py
  • Binary files, such as .docx, .pdf, iamges, spreadsheets, and executable programs(.exe)

steps to read/write files

  1. call the open() function to return a File object
  2. Call the read() or write() method on the File object
  3. Close the file by calling the close() method on the File object

To open the file in 'reading plaintext' mode (read mode):

>>> helloFile=open('/user/kaiming/Python/hello.txt')

>>> helloFile=open('/user/kaiming/Python/hello.txt', 'r')

where 'r' stands for read mode

the call to open() returns a File object, and assigned to the variable helloFile

To get a list of string values from the file, one string for each line of text, use readline() function

Writing to files >>> open ('hello.txt', 'w') # write mode >>> open ('hello.txt', 'a') # append mode

Note:

  1. when a file is opened in read mode, Python lets you only read data from

the file; you can't write or modify it in any way.

  1. if the filename passed to open() does not exist, both

write and append mode will create a new, blank file

>>> baconFile = open('bacon.txt', 'w')  # create a blank file named 'bacon.txt'
>>> baconFile.write('Hello world!\n')
13
>>> baconFile.close()
>>> baconFile = open('bacon.txt', 'a')
>>> baconFile.write('Bacon is not a vegetable.')
25
>>> baconFile.close()
>>> baconFile = open('bacon.txt')
>>> content = baconFile.read()
>>> baconFile.close()
>>> print(content)
Hello world!
Bacon is not a vegetable.

Created: 2019-03-06 周三 06:13

Emacs 25.3.1 (Org mode 8.2.10)

Validate

最新文章

  1. 移动到web整理
  2. jquery插件之tab标签页或滑动门
  3. Neo4j Cypher运行示例
  4. nodejs-express 报错View is not a constructor
  5. BAT批处理(二)
  6. git 第一次初始化
  7. U3D UGUI学习2 - Canvas
  8. Android SDK Manager无法更新问题解决
  9. 再也不用担心ie下console.log报错了。。。
  10. Unity Diffuse Metal Shader Mod
  11. python【第二篇】列表、元组、字典及文件操作
  12. 10 Powerful Apache Modules--reference
  13. C# 2 运算符 if
  14. 2016WHD.china世界云计算日·北京站即将召开
  15. ASP.NET MVC 使用TempData
  16. Banner图二三事
  17. 7.12 其他面向对象设计原则3: 依赖倒置原则DIP
  18. 2019-4-22 jdbc学习笔记
  19. Spark中master与worker的进程RPC通信实现
  20. vux安装中遇到的坑

热门文章

  1. Code First:Fluent API
  2. E20170602-ts
  3. Android内存管理(14)*使用开源库LeakCanary检查内存泄漏
  4. log4net 简易封装
  5. Redis基础---消息通信模式
  6. multiprocessing的进程通信Pipe和Queue
  7. js操作Attribute,控件的各种属性.....maxlength,style...
  8. Windows下重置MySQL密码【MYSQL】
  9. 为什么我的对象被 IntelliJ IDEA 悄悄的修改了?
  10. ES6:Generator函数(1)