/ 写在前面 – 我热爱技术、热爱开源。我也相信开源能使技术变得更好、共享能使知识传播得更远。但是开源并不意味着某些商业机构/个人可以为了自身的利益而一味地索取,甚至直接剽窃大家曾为之辛勤付出的知识成果,所以本文未经允许,不得转载,谢谢/


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:

  1. # Dinner
  2. * rice
  3. * bacon
  4. * beef
  5. * eggplant
  1. # file_reading.py
  2. with open('shopping_list.md') as file_object:
  3. contents = file_object.read()
  4. print(contents)
  5. '''
  6. output:
  7. # Dinner
  8. * rice
  9. * bacon
  10. * beef
  11. * eggplant
  12. '''

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:
  • 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:

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. 1. Rice
  2. 2. Bacon
  3. 3. Beef
  4. 4. Eggplant

Read file line by line:

  1. # file_reading.py
  2. filename = "shopping_list.md"
  3. with open(filename) as file_object:
  4. for line in file_object:
  5. print(line + "# This is an empty line.")
  6. '''
  7. output:
  8. 1. Rice
  9. # This is an empty line.
  10. 2. Bacon
  11. # This is an empty line.
  12. 3. Beef
  13. # This is an empty line.
  14. 4. Eggplant
  15. # This is an empty line.
  16. '''

Make a list of lines from a file using .readlines() .

When you use with , the file object returned by open() is only available inside the with block that contains it. If you want to retain access to a file’s contents outside the with block, you can store the file’s lines in a list inside the block and then work with that list. You can process parts of the file immediately and postpone some processing for later in the program.

An example:

  1. # file_reading.py
  2. filename = "shopping_list.md"
  3. with open(filename) as file_object:
  4. lines = file_object.readlines()
  5. for line in lines:
  6. print(line.rstrip())
  7. '''
  8. output:
  9. 1. Rice
  10. 2. Bacon
  11. 3. Beef
  12. 4. Eggplant
  13. '''

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
  1. filename = "bullshit"
  2. with open(filename, 'w') as file_object:
  3. 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:

  1. try:
  2. print(5/0)
  3. except ZeroDivisionError:
  4. print("You can divide by 0!")
  5. '''
  6. output:
  7. You can divide by 0!
  8. '''

We can add else block after try-except block. Any code that depends on the try block executing successfully goes in the else block.

  1. try:
  2. print(5/0)
  3. except ZeroDivisionError:
  4. print("You can divide by 0!")
  5. else:
  6. print("Success!")
  7. '''
  8. output:
  9. You can divide by 0!
  10. '''

Another version (change 5/0 to 5/2 ) :

  1. try:
  2. print(5/2)
  3. except ZeroDivisionError:
  4. print("You can divide by 0!")
  5. else:
  6. print("Success!")
  7. '''
  8. output:
  9. 2.5
  10. Success!
  11. '''

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 the try statement. The only code that should go in a try statement is code that might cause an exception to be raised. Sometimes you’ll have additional code that should run only if the try block was successful; this code goes in the else block. The except block tells Python what to do in case a certain exception arises when it tries to run the code in the try 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:

  1. A piece of data to store.
  2. A file object it can use to store the data.

Storing data example:

  1. import json
  2. numbers = list(range(1, 20, 2))
  3. filename = "data.json"
  4. with open(filename, 'w') as file_object:
  5. json.dump(numbers, file_object)

Loading data example:

  1. import json
  2. filename = 'data.json'
  3. with open(filename, 'r') as f_obj:
  4. num = json.load(f_obj)
  5. print(num)
  6. '''
  7. output:
  8. [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
  9. '''

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 .