高级编程技术_课后作业(十)

说明

下面为课本上第十章动手试一试中的部分习题


10-1

Python学习笔记:
        在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python知识,其中每一行都以“In Python you can”打头。将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with 代码块外打印它们。
code:
f_name = 'learing_python.txt'
with open(f_name) as file_obj:
    contents = file_obj.read()
    print('First print:')
    print(contents)

with open(f_name) as file_obj:
    print('Second print:')
    for line in file_obj:
        print(line.rstrip())

with open(f_name) as file_obj:
    lines = file_obj.readlines()
print('Third print:')
for line in lines:
    print(line.rstrip())

result:


10-2

C语言学习笔记:
        可使用方法replace() 将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的'dog' 替换为'cat':
        读取你刚创建的文件learning_python.txt中的每一行,将其中的Python都替换为另一门语言的名称,如C。将修改后的各行都打印到屏幕上。
code:
f_name = 'learing_python.txt'

with open(f_name) as file_obj:
    lines = file_obj.readlines()
    
for line in lines:
    print((line.replace('Python', 'C++')).rstrip())

result:


10-3

访客:
        编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中。
code:
f_name = 'guest.txt'

name = input("Who are you, please enter your name here:")

with open(f_name, 'w') as file_obj:
    file_obj.write(name)
result:

猜你喜欢

转载自blog.csdn.net/zero_s_qiu/article/details/79860285
今日推荐