reading/writing files in Python

 

 

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值