本文代码是在jupyter中实现的,仅为了自我督促学习python之用。
10-1 Python 学习笔记:在文本编辑器中新建一个文件,写几句话来总结一下你至
此学到的 Python知识,其中每一行都以“In Python you can”打头。将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在 with 代码块外打印它们。
代码:
print("第一次打印:")
with open('python_note.txt') as file_object: # 创建的文件叫“python_note.txt”,储存在运行环境中
contents = file_object.read()
print(contents)
print("第二次打印:")
with open('python_note.txt') as file_object:
for line in file_object:
print(line.rstrip()) # rstrip()是为了消除多余的空白行
print("第三次打印:")
with open('python_note.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
运行结果:
第一次打印:
In Python you can create functions.
In Python you can use a for loop to traverse the entire list.
In Python you can create dictionaries.
第二次打印:
In Python you can create functions.
In Python you can use a for loop to traverse the entire list.
In Python you can create dictionaries.
第三次打印:
In Python you can create functions.
In Python you can use a for loop to traverse the entire list.
In Python you can create dictionaries.
10-2 C 语言学习笔记:可使用方法 replace() 将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的 ‘dog’ 替换为 ‘cat’ :
message = “I really like dogs.”
message.replace(‘dog’, ‘cat’)
‘I really like cats.’
读取你刚创建的文件 learning_python.txt中的每一行,将其中的 Python都替换为另一门语言的名称,如 C。将修改后的各行都打印到屏幕上。
代码:
with open('python_note.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip()) # 原来的内容
new_line=line.replace('Python', 'C') # 替换
print(new_line) # 替换后的内容
运行结果:
In Python you can create functions.
In C you can create functions.
In Python you can use a for loop to traverse the entire list.
In C you can use a for loop to traverse the entire list.
In Python you can create dictionaries.
In C you can create dictionaries.
备注:
在Windows系统中,在文件路径中使用反斜杠( \ )而不是斜杠( / )