12. python 文件读写

1. 可读

my_file = open('myfile.txt', 'r')  //read

2. 可写

my_file = open('myfile.txt', 'w')  //write

3. 追加

my_file = open('myfile.txt', 'a')  //append

  

3步操作写入:

test = 'this is first line。\n this is second line. \n this is last line'

myfile = open('my.txt', 'w')
myfile.write(test)
myfile.close()

  

4. 读取操作

file = open('my.txt', 'r')  // 把文件存到file变量

content = file.read() // 读取file内容

content = file.readlines() // 读取所有行

content = file.readline() // 读取第一行

content = file.readline() // 读取第二行

print(content)

  

posted @ 2017-03-18 00:07  涵叔  阅读(97)  评论(0)    收藏  举报