10-1
在文本编辑器中新建一个文件, 写几句话来总结一下你至此学到的Python知识, 其中每一行都以“In Python you can”打头。 将这个文件命名为learning_python.txt, 并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序, 它读取这个文件, 并将你所写的内容打印三次: 第一次打印时读取整个文件; 第二次打印时遍历文件对象; 第三次打印时将各行存储在一个列表中, 再在with 代码块外打印它们。
#10-1
#打印整个文件
with open('123.txt.txt') as file_object :
contents=file_object.read()
#read()函数读取文件全部内容
print(contents.rstrip())
print()
#逐行读取
''''with open('123.txt') as file_object :
lines=file_object.read()
for line in lines:
print(line)'''
#错误原因 : 当你采用read()函数时,lines是一个字符串,
#因此下面循环变成了遍历lines里面的每一个字符并打印。
#以下是正确方法:
with open('123.txt.txt') as file_object :
for line in file_object :
print(line.rstrip())
print()
#创建列表
with open('123.txt.txt') as file_object :
lines = file_object.readlines()
#readlines()函数:读取每一行并将其存储在一个列表里
for line in lines :
print(line.rstrip())
print()
输出:
in python you can learned computer language
in python you can be got your dream
in python you can be more cautious,more wise
in python you can learned computer language
in python you can be got your dream
in python you can be more cautious,more wise
in python you can learned computer language
in python you can be got your dream
in python you can be more cautious,more wise
10-2
可使用方法replace() 将字符串中的特定单词都替换为另一个单词。
下面是一个简单的示例, 演示了如何将句子中的’dog’ 替换为’cat’:
message = “I really like dogs.”
message.replace(‘dog’, ‘cat’)
’I really like cats.’
读取你刚创建的文件learning_python.txt中的每一行, 将其中的Python都替换为另一门语言的名称, 如C。将修改后的各行都打印到屏幕上。
#10-2
'''
错误示范:
with open('123.txt.txt') as file_object :
for line in file_object :
line.replace('python','C')
print(line)
'''
#PS.为什么这个代码输出结果python并没有变成C?求大神解答。
#正确的:受到 Martijn Garrix这位博主的启发:
with open('123.txt.txt') as file_object :
message=file_object.read()
print(message.replace('python','C').rstrip())
print()
输出:
in C you can learned computer language
in C you can be got your dream
in C you can be more cautious,more wise
附:在命名文件是,不需要自己加后缀,要不然就会像以上代码一样,123.txt.txt
如果少打了一个txt,则会报错
[Errno 2] No such file or directory: ‘123.txt’
PS F:\python homework>