Python编程:从入门到实践 练习答案 Chapter10

本文展示了Python编程中对文件进行读写、追加操作的实例,包括读取文本文件、逐行处理、存储用户输入、处理文件不存在的情况、计算字符串出现次数、使用JSON存储数据等。此外,还涵盖了错误处理和用户交互,如尝试/异常结构、循环读取及验证用户输入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

20211106,20211107 
suspended 2 days for tinkering my desktop. I've bought a 16Gbytes Samsung SDRAM, that's so great.

10-1
with open('learning_python.txt') as file_object:
    contents = file_object.read()
    print(contents)
print('\n')
    
with open('learning_python.txt') as file_object:
    for line in file_object:
        print(line.rstrip())
print('\n')

with open('learning_python.txt') as file_object:
    l_p = []
    for line in file_object:
        l_p.append(line.rstrip())
        
for l in l_p:
     print(l)
     
10-2
with open('learning_python.txt') as file_object:
    contents = []
    for line in file_object:
        contents.append(line.replace('Python', 'C'))
        
for c in contents:
    print(c.rstrip())

10-3
with open('guest.txt', 'w') as file:
    print('enter 1 to quit')
    while True:
        guest = input('plz enter ur name:')
        if guest == '1':
            break
        else:
            file.write(guest + '\n')

10-4
import time
with open('guest.txt', 'w') as file:
    print('enter q to quit')
    while True:
        guest = input('plz enter ur name:')
        if guest == 'q':
            break
        else:
            file.write(guest + ': ' + time.strftime('%Y-%m-%d %H:%M:%S',\
                                 time.localtime()) + '\n')

            print("What's up! " + guest.title())

10-5
with open('reason.txt', 'a') as file:
    print('enter q to quit')
    while True:
        reason = input('why do u like coding:')
        if reason == 'q':
            break
        else:
            file.write(reason + '\n')

10-6
print('\nenter 2 numbers, I will add them ')
num1 = input('first number: ')
num2 = input('second number: ')
try:
    num = float(num1) + float(num2)
except ValueError:
    print('u can only input numbers')
else:
    print('\nanswer: ' + str(num))

10-7
while True:
    print('\nenter 2 numbers, I will add them ')
    print('enter "q" to quit')
    num1 = input('first number: ')
    if num1 == 'q':
        break
    else:
        num2 = input('second number: ')
        try:
            num = float(num1) + float(num2)
        except ValueError:
            print('u can only input numbers')
        else:
            print('\nanswer: ' + str(num))

10-8
try:
    with open('cats.txt') as f1:
        contents1 = f1.read()
        print('cats:\n' + contents1)


    with open('dogs.txt') as f2:
        contents2 = f2.read()
        print('\ndogs:\n' + contents2)
        
except FileNotFoundError:
    print('u should put files in the same place of this .py')
       
   
10-9
try:
    with open('cats.txt') as f1:
        contents1 = f1.read()
        print('cats:\n' + contents1)


    with open('dogs.txt') as f2:
        contents2 = f2.read()
        print('\ndogs:\n' + contents2)
        
except FileNotFoundError:
    pass

-------------------------------------------------------------------------------    
REVISED:
filenames = ['cats.txt', 'dogs.txt']

for filename in filenames:
    
    try:
        with open(filename) as f:
            contents = f.read()

    except FileNotFoundError:
        pass

    else:
        print("\nReading file: " + filename)
        print(contents)

-------------------------------------------------------------------------------

10-10
with open('Hard Times.txt', 'r', encoding='utf-8') as f: 
#---------------------------------------------, 'r', encoding='utf-8 is pivotal
    c = f.read()
n = c.lower().count('hard')
print("nums of 'the': " + str(n)) 

 
 10-11
import json
num = int(input('plz enter ur favorite number:'))
with open('favorite_number.json','w') as f:
    json.dump(num, f)
    
with open('favorite_number.json') as f:
    nums = json.load(f)
    print(nums)
    
10-12
import json
try:
    with open('george.json') as f:
        num = json.load(f)

except FileNotFoundError:
    with open('george.json','w') as f:
        num = int(input('plz enter ur favorite number:'))
        json.dump(num, f)

else:
    print('ur favorite num is ' + str(num))
    
10-13
import json

def get_stored_username():
    """Get stored username if available."""
    filename = 'username.json'
    try:
        with open(filename) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """Prompt for a new username."""
    username = input("What is your name? ")
    filename = 'username.json'
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
    return username

def verify(username):
    man = input('are u ' + username.title() + ' ?(y/n)' )
    if man == 'y':
        print("Welcome back, " + username + "!")
    else:
        username = get_new_username()
        print("We'll remember you when you come back, " + username + "!")
        

def greet_user():
    """Greet the user by name.""" 
    username = get_stored_username()
    if username:
        verify(username)
    else:
        username = get_new_username()
        print("We'll remember you when you come back, " + username + "!")
        
greet_user()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值