Python文件写入

###write method 1
data = ["dog","cat","kcock"]
with  open('c:/users/liutz/key.dat','w') as f:
    f.write('I am wriyting data in binary file\n')
    f.write("let's write   another list\n ")
    for pet in data:
        f.write(pet+"\n")
###write method 2
f= open('hello.txt','w',encoding='utf-8')
f.write("I am a teacher\n")
f.write("wellcome to Python World!\n")
mylist = ['Apple','Orange','Banana']
f.write(str(mylist))
f.close()
###read file ###
f= open('hello.txt','r',encoding='utf-8')
lines = f.readlines()
print(lines[0])
print(lines[1])
print(lines[2])
print("---- read file------")
for line in lines:
    print(line+'\n')

f.close()