Python 读取文件的三种常见方法
- 使用open()函数打开文件,并使用read()方法读取文件的内容。例如:
file = open("filename.txt", "r")
content = file.read()
file.close()
- 使用with语句打开文件,并使用readlines()方法读取文件的内容。例如:
with open("filename.txt", "r") as file:content = file.readlines()
- 使用for循环逐行读取文件的内容。例如:
with open("filename.txt", "r") as file:for line in file:# 处理每一行的内容
小知识: 由于文件读写时都有可能产生IOError,一旦出错,后面的f.close()就不会调用,产生异常。Python引入了with语句来自动帮我们调用close()方法。
Python 写入文件的三种常见方法
- 使用open()函数打开文件,并使用write()方法写入内容。例如:
file = open("filename.txt", "w")
file.write("Hello, World!")
file.close()
- 使用with语句打开文件,并使用write()方法写入内容。例如:
with open("filename.txt", "w") as file:file.write("Hello, World!")
- 使用open()函数打开文件,并使用writelines()方法写入多行内容。例如:
file = open("filename.txt", "w")
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file.writelines(lines)
file.close()
作业
- 有一个数据文件 data.txt,里面有1000个浮点数,读取该文件,并完成如下要求:
- 求取其最大值和最小值,并打印出来;
- 求取其平均值,并打印出来;
- 求取所有数字的和,并打印出来。