print “\thello world!”
‘’’#同一文件夹里
with open(‘pi.cpp’) as file_obj:
content = file_obj.read()
print(content)
‘’’
‘’’#相对路径
with open(‘text_file\pi2.cpp’) as file_obj2:
content2 = file_obj2.read()
print(content2)
‘’’
‘’’#逐行读取文件
with open(‘pi.cpp’) as file_obj:
for line in file_obj:
print(line.rstrip())
‘’’
‘’’#创建一个包含文件各行内容的列表,可在with代码块外使用该列表
with open(‘pi.cpp’) as file_obj:
lines = file_obj.readlines()
for line in lines:
print(line.rstrip())
‘’’
print ‘\n\thello world!’
#先清空所有文件内容,写入多行文件,需要在文本末尾加换行符
file_name = ‘ppii.cpp’
with open(file_name, ‘w’) as file_objp:
file_objp.write(‘I love programming.\n’)
file_objp.write(‘programming\n’)
#附加到文件,内容加在文件末尾
fil_nam = ‘ppii.cpp’
with open(fil_nam, ‘a’) as fil_obj:
fil_obj.write(‘I love programming,too.\n’)