第一节
1 介绍了Python的文件操作函数open()
2 比如f = open("out.txt" , "w")是表示打开可写的方式打开out.txt
3 任何打开的文件都要进行close,比如f.close()
第二节
1 介绍了我们以"w"方式打开文件的write()函数
2 比如f = open("out.txt" , "w")是表示打开可写的方式打开out.txt,然后我们f.write("haha")是把"haha"字符串写入到out.txt中
3 练习:把my_list中的每一项都写到文件output.txt中,并且在每一项后面加上"\n"
my_list = [i**2 for i in range(1,11)]
my_file = open("output.txt", "r+")
# Add your code below!
for num in my_list:
my_file.write(str(num)+"\n")
my_file.close()
第三节
1 介绍了我们以"r"方式打开文件的read()函数
2 练习:以"r"方式打开output.txt,利用read()函数输出这些值
my_file = open("output.txt" , "r")
print my_file.read()
my_file.close()
第四节
1 介绍了readline()函数用来读入一行
2 练习:以"r"方式打开text.txt文件,然后输出三行读入的readline
# text.txt
I'm the first line of the file!
I'm the second line.
Third line here, boss.
# code
my_file = open("text.txt" , "r")
print my_file.readline()
print my_file.readline()
print my_file.readline()
my_file.close()
第五节
1 介绍了with...as...结构的使用
2 with open("file","mode") as variable:
# Read or write to the file