Python3-文件操作
一、读取文件
---open函数的第一个参数是要打开的文件名(文件名区分大小写)
---read函数可以一次性读入并返回文件的所有内容。
---close函数负责关闭文件
注意:如果忘记关闭文件,会造成系统资源消耗,而且会影响到后续对文件的操作。方法执行后,会把文件指针移动到文件的末尾。
代码示例:
# 打开要读取的文件
file = open("test.txt")
# 写入文件内容
content = file.read()
print(content)
# 关闭文件
file.close()
二、向文件写入内容
---open函数默认以只读方式打开文件,并且返回文件对象。
以下是文件读取的各种模式:
代码示例:
# 打开要读取的文件
file = open("test.txt", "w", encoding="utf-8")
# 读取文件内容
content = file.write("你好")
# 关闭文件
file.close()
三、按行读取文件内容(读取大文件的正确姿势)
readline函数可以一次读取一行内容,函数执行后,会把文件指针移动到下一行,准备再次读取,减少对内存的占用。
代码示例:
# 打开要读取的文件
file = open("test.txt", encoding="utf-8")
# 读取文件内容
while True:
content = file.readline()
if not content:
break
print(content, end="") # 改变end参数的默认值,使之不换行
# 关闭文件
file.close()
四、小文件复制
代码示例:
# 打开要读取和写入的文件
file_read = open("test.txt", encoding="utf-8")
file_write = open("test_1.txt", "w", encoding="utf-8")
# 读取文件内容,并向另一文件写入内容
content = file_read.read()
file_write.write(content)
# 关闭文件
file_read.close()
file_write.close()
五、大文件复制
代码示例:
# 打开要读取和写入的文件
file_read = open("test.txt", encoding="utf-8")
file_write = open("test_1.txt", "w", encoding="utf-8")
# 读取文件内容,并向另一文件写入内容
while True:
content = file_read.readline()
if not content:
break
file_write.write(content)
# 关闭文件
file_read.close()
file_write.close()
六、使用OS模块对文件和目录进行操作