第一节
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...结构的使用
2with open("file","mode") as variable:
# Read or write to the file
本文详细介绍了Python中文件操作的基础知识,包括如何使用open()函数打开文件,以不同的模式(如'r', 'w')进行读写操作,以及如何通过write()函数将数据写入文件。还展示了如何通过循环遍历列表并将每个元素写入文件,以及如何以'r'模式读取已写入的文件并输出其内容。
1074

被折叠的 条评论
为什么被折叠?



