/ 写在前面 – 我热爱技术、热爱开源。我也相信开源能使技术变得更好、共享能使知识传播得更远。但是开源并不意味着某些商业机构/个人可以为了自身的利益而一味地索取,甚至直接剽窃大家曾为之辛勤付出的知识成果,所以本文未经允许,不得转载,谢谢。/
Files
Read
Use open()
function to open a file. The open()
function returns an object representing the file.
Except open()
function, we also have close()
function, but the problem is that we don’t know when a file is on longer needed. Therefore, keyword with
is a better choice, which closes the file once access to it is no longer needed. Just remember: All we need to do is trust Python will automatically close the file that we opened as desired when the time is right.
The object representing a file has a function called .read()
which stores all the contents of that file in one long string.
Here is what’s in file shoppint_list.md:
# Dinner
* rice
* bacon
* beef
* eggplant
# file_reading.py
with open('shopping_list.md') as file_object:
contents = file_object.read()
print(contents)
'''
output:
# Dinner
* rice
* bacon
* beef
* eggplant
'''
Path:
- Relative path
- Linux and macOS:
with open('text_files/filename.txt') as file_object:
- Windows:
with open('text_files\filename.txt') as file_object:
- Linux and macOS:
- Absolute path
- Linux and macOS:
file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
- Windows:
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
- Then use:
with open(file_path) as file_object:
- Linux and macOS:
Note:
Windows systems will sometimes interpret forward slashes (
/
) in file paths correctly. If you’re using Windows and you’re not getting the results you expect, make sure you try using backslashes (\
).
Contents in shoppint_list.md:
1. Rice
2. Bacon
3. Beef
4. Eggplant
Read file line by line:
# file_reading.py
filename = "shopping_list.md"
with open(filename) as file_object:
for line in file_object:
print(line + "# This is an empty line.")
'''
output:
1. Rice
# This is an empty line.
2. Bacon
# This is an empty line.
3. Beef
# This is an empty line.
4. Eggplant
# This is an empty line.
'''
Make a list of lines from a file using .readlines()
.
When you use
with
, the file object returned byopen()
is only available inside the with block that contains it. If you want to retain access to a file’s contents outside thewith
block, you can store the file’s lines in a list inside the block and then workwith
that list. You can process parts of the file immediately and postpone some processing for later in the program.
An example:
# file_reading.py
filename = "shopping_list.md"
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
'''
output:
1. Rice
2. Bacon
3. Beef
4. Eggplant
'''
Note: When Python reads from a text file, it interprets all text in the file as a string.
Write
When Python writes to a file, it will create a file with given file name if the file doesn’t exist. Note that we need to give second parameter to open()
function.
open()
function has below second parameters:
'r'
- read mode'w'
- write mode'a'
- append mode'r+'
- a mode that allows us to read and write to the file
filename = "bullshit"
with open(filename, 'w') as file_object:
file_object.write("I love programming.\n")
Exceptions
Exceptions are special objects in Python to manage errors that arise during a program’s excution.
Exceptions are handled in try-except
blocks.
When we think an error may occur, we can write a try-except
block to handle the exception that might be raised.
Let’s see an example:
try:
print(5/0)
except ZeroDivisionError:
print("You can divide by 0!")
'''
output:
You can divide by 0!
'''
We can add else
block after try-except
block. Any code that depends on the try
block executing successfully goes in the else
block.
try:
print(5/0)
except ZeroDivisionError:
print("You can divide by 0!")
else:
print("Success!")
'''
output:
You can divide by 0!
'''
Another version (change 5/0
to 5/2
) :
try:
print(5/2)
except ZeroDivisionError:
print("You can divide by 0!")
else:
print("Success!")
'''
output:
2.5
Success!
'''
Important Note: Any code that depends on the try
block succeeding is added to the else
block.
The
try-except-else
block works like this: Python attempts to run the code in thetry
statement. The only code that should go in atry
statement is code that might cause an exception to be raised. Sometimes you’ll have additional code that should run only if thetry
block was successful; this code goes in theelse
block. Theexcept
block tells Python what to do in case a certain exception arises when it tries to run the code in thetry
statement.
Common exceptions:
ZeroDivisionError
FileNotFoundError
TypeError
Storing Data
A simple way to store data involves using the json
module, which allows us to dump simple Python data structures into a file and load the data from that file the next time the program runs.
The JSON (JavaScript Object Notation) format was originally developed for JavaScript. However, it has since become a common format used by many languages, including Python.
json.dump()
is to store data. json.load()
is to load data.
json.dump()
takes 2 arguments:
- A piece of data to store.
- A file object it can use to store the data.
Storing data example:
import json
numbers = list(range(1, 20, 2))
filename = "data.json"
with open(filename, 'w') as file_object:
json.dump(numbers, file_object)
Loading data example:
import json
filename = 'data.json'
with open(filename, 'r') as f_obj:
num = json.load(f_obj)
print(num)
'''
output:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
'''
In Python, we can return None
! This is a good practice: a function should either return the value you’re expecting, or it should return None
.