读取整个文件
# file_reader.py
# 在file_reader.py所在的目录中查找pi_digits.txt
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
逐行读取
# file_reader.py
# 在file_reader.py所在的目录中查找pi_digits.txt
with open('pi_digits.txt') as file_object:
for line in file_object:
print(line)
创建一个包含文件各行内容的列表
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
使用文件的内容
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
print(pi_string)
print(len(pi_string))
相对路径
# Linux和OS X
with open('text_files/filename.txt') as file_object:
# windows 在文件路径中使用反斜杠(\)而不是斜杠(/)
with open('text_files\filename.txt') as file_object:
绝对路径
# Linux和OS X
file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
with open(file_path) as file_object:
# windows 在文件路径中使用反斜杠(\)而不是斜杠(/)
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:
写入空文件
filename = 'programming.txt'
# 写入的文件不存在,函数open()将自动创建它,如果指定的文件已经存在,Python将在返回文件对象前清空该文件
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
读取模式(‘r’)、写入模式(‘w’)(覆盖掉)、附加模式(‘a’)或能够读取和写入文件的模式(‘r+’)
写入多行
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")
附加到文件
# 以附加模式打开文件,不会在返回文件对象前清空文件,而写入到文件的行都将添加到文件末尾
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")