一.从文件中读取数据

1.读取整个文件

pi_digits.txt

  1. 3.1415926535
  2. 8979323846
  3. 2643383279
  1. with open('pi_digits.txt') as file_object:
  2. contents = file_object.read()
  3. print(contents)
  1. 3.1415926535
  2. 8979323846
  3. 2643383279

相比于原始文件,该输出唯一不同的地方是末尾多了一个空行。为何会多出这个空行呢?因为read() 到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一 个空行。要删除多出来的空行,可在print 语句中使用rstrip() :

  1. with open('pi_digits.txt') as file_object:
  2. contents = file_object.read()
  3. print(contents.rstrip())
  1. 3.1415926535
  2. 8979323846
  3. 2643383279

2.文件路径

这行代码让Python到文件夹python_work下的文件夹text_files中去查找指定的.txt文件:

相对文件路径

  1. with open('text_files\filename.txt') as file_object:

绝对文件路径

  1. file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
  2. with open(file_path) as file_object:

3.逐行读取

  1. filename = 'pi_digits.txt'
  2. with open(filename) as file_object:
  3. for line in file_object:
  4. print(line)
  1. 3.1415926535
  2. 8979323846
  3. 2643383279

为何会出现这些空白行呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而print 语句也会加上一个换行符,因此每行末尾都有两个换行符:一个来自文件,另一个来自print 语句。要消除这些多余的空白行,可在print 语句中使用rstrip() :

  1. filename = 'pi_digits.txt'
  2. with open(filename) as file_object:
  3. for line in file_object:
  4. print(line.rstrip())
  1. 3.1415926535
  2. 8979323846
  3. 2643383279

4.创建一个包含文件各行内容的列表

使用关键字with 时,open() 返回的文件对象只在with 代码块内可用。如果要在with代码块外访问文件的内容,可在with 代码块内将文件的各行存储在一个列表中,并在with 代码块外使用该列表:你可以立即处理文件的各个部分,也可推迟到程序后面再处理。

  1. filename = 'pi_digits.txt'
  2. with open(filename) as file_object:
  3. lines = file_object.readlines()
  4. for line in lines:
  5. print(line.rstrip())

readlines() 从文件中读取每一行,并将其存储在一个列表中。

5.使用文件的内容

  1. filename = 'pi_30_digits.txt'
  2. with open(filename) as file_object:
  3. lines = file_object.readlines()
  4. pi_string = ''
  5. for line in lines:
  6. pi_string += line.strip()
  7. print(pi_string)
  8. print(len(pi_string))
  1. 3.141592653589793238462643383279
  2. 32

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

6.包含一百万位的大型文件

前面我们分析的都是一个只有三行的文本文件,但这些代码示例也可处理大得多的文件。如果我们有一个文本文件,其中包含精确到小数点后1 000 000位而不是30位的圆周率值,也可创建一个包含所有这些数字的字符串。为此,我们无需对前面的程序做任何修改,只需将这个文件传递给它即可。在这里,我们只打印到小数点后50位,以免终端为显示全部1000 000位而不断地翻滚:

  1. filename = 'pi_million_digits.txt'
  2. with open(filename) as file_object:
  3. lines = file_object.readlines()
  4. pi_string = ''
  5. for line in lines:
  6. pi_string += line.strip()
  7. print(pi_string[:52] + "...")
  8. print(len(pi_string))
  1. 3.14159265358979323846264338327950288419716939937510...
  2. 1000002

7.圆周率值中包含你的生日吗

  1. filename = 'pi_million_digits.txt'
  2. with open(filename) as file_object:
  3. lines = file_object.readlines()
  4. pi_string = ''
  5. for line in lines:
  6. pi_string += line.rstrip()
  7. birthday = input("Enter your birthday, in the form mmddyy: ")
  8. if birthday in pi_string:
  9. print("Your birthday appears in the first million digits of pi!")
  10. else:
  11. print("Your birthday does not appear in the first million digits of pi.")
  1. Enter your birthdate, in the form mmddyy: 120372
  2. Your birthday appears in the first million digits of pi!

二.写入文件

1.写入空文件

  1. filename = 'programming.txt'
  2. with open(filename, 'w') as file_object:
  3. file_object.write("I love programming.")

在这个示例中,调用open() 时提供了两个实参。第一个实参也是要打开的文件的名称;第二个实参(’w’ )告诉Python,我们要以写入模式打开这个文件。打开文件时,可指定读取模式(’r’ )、写入模式(’w’ )、附加模式(’a’ )或让你能够读取和写入文件的模式(’r+’ )。如果你省略了模式实参,Python将以默认的只读模式打开文件。 如果你要写入的文件不存在,函数open() 将自动创建它。然而,以写入(’w’ )模式打开文件时千万要小心,因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件。

2.写入多行

  1. filename = 'programming.txt'
  2. with open(filename, 'w') as file_object:
  3. file_object.write("I love programming.")
  4. file_object.write("I love creating new games.")
  1. I love programming.I love creating new games.

函数write() 不会在你写入的文本末尾添加换行符,因此如果你写入多行时没有指定换行符,文件看起来可能不是你希望的那样

  1. filename = 'programming.txt'
  2. with open(filename, 'w') as file_object:
  3. file_object.write("I love programming.\n")
  4. file_object.write("I love creating new games.\n")

3.附加到文件

如果你要给文件添加内容,而不是覆盖原有的内容,可以附加模式打开文件。你以附加模式打开文件时,Python不会在返回文件对象前清空文件,而你写入到文件的行都将添加 到文件末尾。如果指定的文件不存在,Python将为你创建一个空文件。

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