# -*- coding: utf-8 -*-
"""
Spyder Editor
Author:Linguiyuan
"""
def main():
text = """林桂源,
你好啊,
你要好好加油哦!"""
f_w = open("hello.txt",'w')
f_w.write(text)
f_w.close()
f_r = open("hello.txt",'r')
while True:
line = f_r.readline()
if len(line)==0:
break
print(line,end='')
f_r.close()
if __name__ == '__main__':
main()
首先,我们通过指明我们希望打开的文件和模式来创建一个file 类的实例。模式可以为读模式(’r’)、写模式(’w’)或追加模式(’a’)。
在我们的例子中,我们首先用写模式打开文件,然后使用file 类的write 方法来写文件,最后我们用close 关闭这个文件。
接下来,我们再一次打开同一个文件来读文件。如果我们没有指定模式,读模式会作为默认的模式。在一个循环中,我们使用readline 方法读文件的每一行。这个方法返回包括行末换行符的一个完整行。所以,当一个空的字符串被返回的时候,即表示文件末已经到达了,于是我们停止循环。
默认情况下,print() 函数将文本和自动生成的新行打印到屏幕。我们指定end=”来制约新行的产生,因为从文件中读出的行已经用了换行符。最后,关闭文件。
使用readlines():
使用readlines()读文件,每次读取多行数据
file = open("hello.txt","r")
lines = file.readlines()
for line in lines:
print (line)
file.close()
使用read():
使用read()读文件,一次性读出所有内容
file = open("hello.txt")
content = file.read()
print(content)
file.close()
使用writelines()写入文件:
f = open("hello.txt","w+")
li = ["hello huangxiaojuan\n","ye ye ye ye ye"]
f.writelines(li)
f.close()
使用write(),以追加的形式写入:
f = open("hello.txt","a+")
new_context = "\nI Love You"
f.write(new_context)
f.close()