w (写入模式) a (附加模式) r+(读写模式),python默认以读写的方式打开文件 文件的读取
with open('text_files/pi.txt') as file_object:
contents=file_object.read()
print(contents)
显示文件路径时,windows系统使用的时反斜杠(),不是斜杠(/),在代码中使用斜杠(/),’'属于转义字符
with open('text_files/pi.txt') as file_object:
for line in file_object:
print(line)
with open('text_files/pi.txt') as file_object:
lines=file_object.readlines()
print(lines)
for line in lines:
print(line.rstrip())
with open('learning_python.txt') as file_object:
print("第一次打印")
print(file_object.read())
print("第二次打印")
with open('learning_python.txt') as file_object:
for line in file_object:
print(line)
print("第三次打印")
with open('learning_python.txt') as file_object:
lines=file_object.readlines()
for line in lines:
print(line)
"""
第一次打印
In python you can:变量和简单数据类型
In python you can:注释
In python you can:列表
In python you can:if语句
In python you can:字典
In python you can:元组
In python you can:while
In python you can:for
In python you can:函数
In python you can:类文件和异常
第二次打印
In python you can:变量和简单数据类型
In python you can:注释
In python you can:列表
In python you can:if语句
In python you can:字典
In python you can:元组
In python you can:while
In python you can:for
In python you can:函数
In python you can:类文件和异常
第三次打印
In python you can:变量和简单数据类型
In python you can:注释
In python you can:列表
In python you can:if语句
In python you can:字典
In python you can:元组
In python you can:while
In python you can:for
In python you can:函数
In python you can:类文件和异常
"""
with open('learning_python.txt') as file_object:
for line in file_object:
print(line.replace('python','C'))
写入文件,不是附加
filename='programming.txt'
with open(filename,'r+')as file_object:
file_object.write('hi,你好哇。')
read=file_object.read()
print(read)
附件模式写入文件
filename='programming.txt'
with open(filename,'a+')as file_object:
file_object.write('hi,你好哇。\n')
file_object.write('我是flyable\n')
filename='programming.txt'
with open(filename,'r+')as file_object:
read=file_object.read()
print(read)
name=input('请输入你的名字:')
with open('guest.txt','w')as file_project:
file_project.write(name)
while True:
name=input('输入"q",结束,请输入你的名字:')
if name=='q':
break
else:
print(f'欢迎{name}的到来!')
with open('guest_book.txt','a+')as file_project:
file_project.write(name+'\n')
while True:
reason=input('你为什么喜欢编程呢?')
if reason=='q':
break
else:
with open('resons.txt','a')as file_project:
file_project.write(reason+'\n')
|