with open('test.txt') as file_object: # 使用with关键字后,不需要手动关闭文件
contents = file_object.read()
print(contents)
Hello,world!
I'm a robot.
Who are you?
2.文件路径
在Linux和OS X中,文件路径的写法
with open('text_files/filename.txt') as file_object:
在Windows中,文件路径的写法 with open('text_files\filename.txt') as file_object:
3.逐行读取
with open('test.txt') as file_object:
for line in file_object:
print("-"+line)
-Hello,world!
-I'm a robot.
-Who are you?
4.创建一个包含文件各行内容的列表
# 使用关键字with时,open()返回的文件对象只在with代码块内可用。# 如果要在with代码块外访问文件的内容,可在with代码块将文件的各行存储在一个列表中,# 并在with代码块外使用该列表with open('test.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print("-"+line)
-Hello,world!
-I'm a robot.
-Who are you?
二、写入文件
1.写入空文件
with open('write_test.txt','w') as file_object:
file_object.write('I love python.')
2.写入多行
with open('write_test.txt','w') as file_object:
file_object.write('I love python.\n')
file_object.write('I love coding.\n')
3.追加到文件
with open('write_test.txt','a') as file_object:
file_object.write("But I am a AI.\n")