1. 打开文件

    1
    2
    3
    4
    5
    6
    """打开文件并打印内容."""


    with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents)

    关键字 with 在不再需要访问文件后将其关闭。在这个程序中,注意到我们调用了函数 open() ,但没有调用 close() ;你也可以调用 open()close() 来打开和关闭文件,但这样做时,如果程序存在 bug,导致 close() 语句未执行,文件将不会关闭,未妥善地关闭文件可能会导致数据丢失或受损。

    通过前面使用的结构,可让 Python 确定关闭文件的恰当时机。

    read() 到达文件末尾时返回一个空的字符串,而将这个空的字符串显示出来就是一个空行,要删除多出来的空行,可在 print 语句中使用 rstrip()

    1
    print(contents.rstrip())
  2. 使用关键字 with 时, open() 返回的文件对象只在 with 代码块内可用。如果要在 with 代码块外访问文件的内容,可在 with 代码块内将文件的各行存储在一个列表中:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    """将文件中的各行存储在一个列表中."""

    filename = 'pi_digits.txt'

    with open(filename) as file_object:
    lines = file_object.readlines()

    for line in lines:
    print(line.rstrip())
  3. 读取文本文件时,Python 将其中的所有文本都解读为字符串。如果你读取的是数字,并要将其作为数值使用,就必须使用函数 int() 将其转换为整数,或使用函数 float() 将其转换为浮点数。

  4. 可使用 replace() 方法将字符串中的特定单词替换为另一个单词:

    1
    2
    3
    4
    5
    6
    7
    """替换字符串中的单词."""

    message = "I really like dogs."
    print(message.replace('dog', 'cat'))

    # 结果为
    # I really like cats.

    然而 message 的内容并没有发生改变:

    1
    2
    3
    4
    5
    6
    7
    8
    """替换字符串中的单词."""

    message = "I really like dogs."
    message.replace('dog', 'cat')
    print(message)

    # 结果为
    # I really like dogs.
  5. 1
    2
    3
    4
    5
    6
    """写入空文件."""

    filename = 'programming.txt'

    with open(filename, 'w') as file_object:
    file_object.write("I love programming.")

    调用 open() 时提供了两个实参,第一个实参是要打开的文件的名称,第二个实参('w')告诉 Python,我们要以写入模式打开这个文件。打开文件时,可指定读取模式('r')、写入模式('w')、附加模式('a')或让你能够读取和写入文件的模式('r+')。

    Python 只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str() 将其转换为字符串格式。

    写入多行时,末尾需要加上换行符:

    1
    2
    3
    4
    5
    6
    7
    """写入多行."""

    filename = 'programming.txt'

    with open(filename, 'w') as file_object:
    file_object.write("I love programming.\n")
    file_object.write("I love creating new games.\n")

    如果你要给文件添加内容,而不是覆盖原有的内容,可以附加模式打开文件,将你写入到文件的行都添加到末尾:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    """附加到文件."""

    filename = 'programming.txt'

    with open(filename, 'a') as file_object:
    file_object.write("I also love finding meaning in large datasets.\n")
    file_object.write("I love creating apps that can run in a browser.\n")

    # 结果为
    # I love programming.
    # I love creating new games.
    # I also love finding meaning in large datasets.
    # I love creating apps that can run in a browser.
  6. 处理异常

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    """处理异常."""

    print("Give me two numbers, and I'll divide them.")
    print("Enter 'q' to quit.")

    while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
    break
    second_number = input("Second number: ")
    if second_number == 'q':
    break
    try:
    answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
    print("You can't divide by 0!")
    else:
    print(answer)

    只有可能引发异常的代码才需要放在 try 语句中。

    依赖于 try 代码块成功执行的代码都放在 else 代码块中,在这个示例中,如果除法运算成功,我们就使用 else 代码块来打印结果, except 代码块告诉 Python,如果出现ZeroDivisionError 异常时该怎么办。

    处理找不到文件的异常:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    """处理找不到文件的异常."""

    filename = 'alice.txt'

    try:
    with open(filename) as f_obj:
    contents = f_obj.read()
    except FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exist."
    print(msg)
  7. 方法 split() 以空格为分隔符将字符串分拆成多个部分,并将这些部分存储在一个列表中,结果是一个包含字符串中所有单词的列表:

    1
    2
    3
    4
    5
    6
    7
    8
    """split()方法."""

    title = "Alice in Wonderland"
    words = title.split()
    print(words)

    # 结果为:
    # ['Alice', 'in', 'Wonderland']
  8. 存储和读取数据

    1
    2
    3
    4
    5
    6
    7
    8
    9
    """存储数据."""

    import json

    numbers = [2, 3, 5, 7, 11, 13]

    filename = 'numbers.json'
    with open(filename, 'w') as f_obj:
    json.dump(numbers, f_obj)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    """读取数据."""

    import json

    filename = 'numbers.json'

    with open(filename) as f_obj:
    numbers = json.load(f_obj)

    print(numbers)