博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
reading/writing files in Python
阅读量:6771 次
发布时间:2019-06-26

本文共 1540 字,大约阅读时间需要 5 分钟。

 

 

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

25.3.1 ( mode 8.2.10)

转载于:https://www.cnblogs.com/code-saturne/p/10393123.html

你可能感兴趣的文章
基于LAMP 搭建PowerDNS
查看>>
关于android8.1实现多个app升级时的注意事项
查看>>
省市县三级联动
查看>>
【高德地图API】从零开始学高德JS API(三)覆盖物
查看>>
IOS的UIScrollView的自动布局
查看>>
我的友情链接
查看>>
DHCP服务器配置
查看>>
Long integer Adder-大整数相加
查看>>
Docker用户指南 之(第二步) Hello world
查看>>
1052. Candy Sharing Game
查看>>
指令寄存器名词解释【一】
查看>>
Xcode6 中 设置安装KSImage 出现错误
查看>>
Yii框架官方指南系列33——扩展Yii:概览
查看>>
ASP.NET中前台javascript与后台代码调用
查看>>
First Blood
查看>>
2015年总结之什么叫软件开发?
查看>>
迈向虚拟化 硬件如何购买?
查看>>
Tomcat详解及SNS系统的部署实现
查看>>
python 图像处理
查看>>
[JDBC] 连接MySQL数据库
查看>>