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

posted @ 2019-02-17 22:50  kaiming_ai  阅读(268)  评论(0编辑  收藏  举报