python第十一天:文件文本的基本操作

'''在python_work下的zxcnm.txt中读出信息'''
with open('python_work/zxsb.txt') as file_object:
    sentences = file_object.readlines()
nu = ''
for sentence in sentences:
    nu += sentence
print (sentence.strip()[:6])
 '''在python_work下的zxcnm.txt中写入信息'''
with open ('python_work/zxcnm.txt','w') as word:
    word.write("张旭草泥马!")

'''两个异常处理'''
print ("Give me 2 num, and i will divide them:")
print ("Enter 'q' to quit.")
while True:
    first_num = input("Please input the first number:")
    if first_num == 'q':
        print ("Thank you for your use!")
        break
    second_num = input("Please input the second num:")
    if second_num == 'q':
        print ("Thank you for your use!")
        break
    
    try:
        ans = int(first_num)/int(second_num)
    except ZeroDivisionError:
          print ("You can't divide 0!")
    else:
        print (ans)   
 
'''第二个'''
flag = False
file_name = 'zxcnm'
try:
    with open(file_name) as zxdsb:
        number =zxdsb.read()
except FileNotFoundError:
print ("This file "+file_name+" not exist! But:")
    flag = True
else:
    print(number)
 
if flag:
    with open ('python_work/zxcnm.txt') as scentence:
        scentences = scentence.readlines()
        for line in scentences:
            print (line.strip())

猜你喜欢

转载自blog.csdn.net/CalvinHARRIS/article/details/82845156