文件
1.读取整个文件
filepath="D:\\test.txt"
file_object=open(filepath)
file_content=file_object.read()
print(file_content)
file_object.close()
>>>
111111111111
222222222222
333333333333
444444444444
555555555555
666666666666
777777777777
888888888888
Process finished with exit code 0
更好的一种写法:
使用with时,open返回的对象只在with代码块中有用;
filepath="D:\\test.txt"
with open(filepath) as file_object:
file_content=file_object.read()
print(file_content)
>>>
111111111111
222222222222
333333333333
444444444444
555555555555
666666666666
777777777777
888888888888
2.逐行读取
filepath="D:\\test.txt"
with open(filepath) as file_object:
for line in file_object:
print(line)
使用with时,open返回的对象只在with代码块中有用;可以将数据存储在列表中,在外边打印;
filepath="D:\\test.txt"
with open(filepath) as file_object:
lines=file_object.readline()
print(lines)
3.使用文件内容
with open(filepath) as file_object:
lines=file_object.readlines()
str=''
for line in lines:
str+=line
print(str)
open函数
1.open函数有两个参数,第一个参数:告诉文件所在位置;第二个参数:告诉python是以写入模式打开该文件还是只读模式打开等
open(filepath,'w'):写入模式打开filepath文件
open(filepath,'r'):读取模式打开filepath文件
2.如果打开的文件不存在,则创建
3.以写入模式打开文件,因为如果指定的文件已经存在,python将在返回文件对象前清空该文件
附加模式
1.如果要给文件添加内容,而不是覆盖原有内容,可以使用附加模型打开文件;以附加模式打开,python不会在返回文件对象前清空文件,而写入的文件都会添加到文件的末尾
open(filepath,'a'):附加模式打开filepath文件