1.读取文件内容
# 1.打开文件
file = open("E:/test.txt")
# 2.读取文件的内容
content = file.read()
print(content)
# 3.关闭文件
file.close()
2.文件指针
"""
默认是在文件的开始位置
执行read方法后,文件指针会来到文件的末尾
也就是read方法只能调用一次;在调用得不到任何信息;
"""
3.文件打开的方式
"""
open函数是默认以只读的方式打开文件
opens("文件名",“文件打开的方式”)
opens("文件名","方式","编码格式(encoding="UTF-8")")
文件的打开方式有:
r 只读的方式打开文件,如果文件不存在就会报异常
w 只写的方式打开文件,文件不存在,创建文件
a 追加的方式打开文件,并将文件指针移动到文件的末尾。如果文件不存在,创建新文件
r+ 读写的方式打开文件,文件指针在文件的开头,如果文件不存在抛异常、
w+ 读写的方式打开文件,如果文件存在就会被覆盖掉,如果文件不存在创建文件;
a+ 读写方式打开文件,并将文件指针移动到文件的末尾,如果文件不存在,创建文件;
"""
4.分行读取文件
file = open("e:/test.txt")
while True:
readline = file.readline()
if not readline:
break
print(readline)
file.close()
5.文件copy
"""
大文件copy
"""
file = open("e:/test.txt")
file2 = open("e:/test2.txt", "w")
while True:
readline = file.readline()
if not readline:
break
print(readline)
file2.write(readline)
file.close()
file2.close()
"""
小文件copy
"""
file = open("e:/test.txt")
file3 = open("e:/test3.txt", "w")
read = file.read()
file3.write(read)
file.close()
file3.close()
6.文件的管理操作