第十章文件和异常

#读取文件操作,
# 当前路径
with open('pi.txt') as file:
print(file.read())
# 绝对路径
with open('D:db.txt') as file:
print(file.read())

# 这样执行打出来的会多一行空白,是因为每个末尾都有一个换行符
filename='pi.txt'
with open(filename) as file:
for line in file:
print(line)
#让圆周率连在一起
filename="pi.txt"
with open(filename) as file:
lines=file.readlines()
p_string=''
for line in lines:
p_string+=line.strip()
print(p_string)
print(len(p_string))

#圆周率有你的生日没有
filename="pi.txt"
with open(filename) as file:
lines=file.readlines()
p=''
for line in lines:
p+=line.rstrip()
birthday=input("Enter you birthday:")
if birthday in p:
print("Your birthday appears in the first million digits of pi")
else:
print("not apperas ")

#总结:readLine 从字面意思可以看出,该方法每次读出一行内容,所以,读取时占用内存小,比较适合大文件,该方法返回一个字符串对象。,ReadLines 一起性读取文中所有的行数,并按行返回到list,方便我们遍历
read() : 一次性读取整个文件内容。推荐使用read(size)方法,size越大运行时间越长


# 写入文件操作
# 指定打开文件时,读取模式r,写入模式w,附加模式a,让你能读取和写入文件的模式r+,如果是省略模式
#则默认只读,如果写入文件不存在,会自动创建,用w时候要小心,如果存在了,会返回对象前清空该文件
filename="li.txt"
with open(filename,'w') as file:
file.write("I love programming. ")
file.write("I love programming. ")
#追加模式a
filename="li.txt"
with open(filename,'a') as file:
file.write("I love dataing. ")
file.write("I love swiming. ")



#异常,如果Try 中的没有问题,那么就输出try 中的内容,如果有问题,就输出except
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")

#else 代码块, 依赖于try 执行成功后的代码块都要放在else 代码块中
print("Give me two number, I will divide it")
while True:
first_number=input(" First number:")
if first_number=='q':
break
second_number=input(" second number:")
try:
answer=int(first_number)/int(second_number)
except ZeroDivisionError:
print("You can't divie by 0")
else:
print(answer)
#文件异常 FileNotFoundError
filename='hell.txt'
try:
with open(filename) as file:
contents= file.read()
except FileNotFoundError:
msg="Sorry,the file "+filename+" not exist"
print(msg)


# 统计文本有多少个单词,这些文件可能不存在
def count_words(filename):
try:
with open(filename) as file:
contents=file.read()
except FileNotFoundError:
msg="sorry,the file not exist"
print(msg)
else:
word=contents.split()
numwords=len(word)
print(filename+" has about "+str(numwords))
filename=['alice.txt','li.txt','pi.txt']
for f in filename:
count_words(f)



#失败时一声不吭,pass 这个表示直接略过,pass 就是不做任何操作
def count_words(filename):
try:
with open(filename) as file:
contents=file.read()
except FileNotFoundError:
pass
else:
word=contents.split()
numwords=len(word)
print(filename+" has about "+str(numwords))
filename=['alice.txt','li.txt','pi.txt']
for f in filename:
count_words(f)


还有json操作,但是我认为书上说的浅。回头补资料
原文地址:https://www.cnblogs.com/lixiaowei395659729/p/13435917.html