在处理文件对象时,最好使用with关键字。其优点是,文件在其套件完成后将正确关闭,即使在某个时刻引发异常。
读
with open('ed.py') as f:
readData = f.read() if readData:
print(readData)
with open('ed.py') as f:
for line in f:
print(line, end='')
写,然后读
with open('xx.txt','w') as f:
f.write("hello\n")
f.write("world")
with open('xx.txt') as f:
for line in f:
print(line, end='')
hello
world
fileName=input("请输入文件名:")
with open(fileName,'w') as f:
f.write("12345\n")
f.write("6789A")
try:
with open(fileName) as f:
f.seek(3)
print(f.read(2))
except FileNotFoundError:
print("文件没有找到")
异常处理
fileName=input("请输入文件名:")
with open(fileName,'w') as f:
f.write("12345\n")
f.write("6789A")
try:
with open(fileName+"cc") as f:
f.seek(3)
print(f.read(2))
except FileNotFoundError:
print("文件没有找到")
请输入文件名:ss.txt
文件没有找到
try:
fileName=input("请输入文件名字:")
f=open(fileName,'w')
while True:
fileStr=input("请输入文件内容:")
f.write(fileStr+"\n")
if fileStr=="%END%":
break
except Exception as inst:
print(inst)
except:
print("输入中断,已经输入内容被保存")
else:
print("输入结束,无异常")
finally:
f.close()
with open(fileName) as f:
readData = f.read()
if readData:
print(readData)
请输入文件名字:xx.txt
请输入文件内容:11
请输入文件内容:22
请输入文件内容:33
输入中断,已经输入内容被保存
11
22
33
请输入文件名字:1.txt
请输入文件内容:11
请输入文件内容:22
请输入文件内容:3
请输入文件内容:%END%
输入结束,无异常
11
22
3
%END%