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.

2. if the filename passed to =open()= does not exist, both
write and append mode will create a new, blank file

*************
#+BEGIN_SRC Python
>>> 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.
#+END_SRC
*************

猜你喜欢

转载自www.cnblogs.com/code-saturne/p/10393123.html