|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
(这个是《零基础入门学习Python》第29讲动动手的第4题)
这是我的有问题的代码:
title = input('请输入文件名:')
str_old = input('请输入需要替换的单词或字符:')
str_new = input('请输入新的单词或字符:')
count = 0
content = []
file = open(title)
for each in file:
if str_old in each:
count += each.count(str_old)
new = file.replace(str_old, str_new)
content.append(new)
print('文件%s中共有%d个【%s】' % (title, count, str_old))
print('您确定要把所有的【%s】替换为【%s】吗?' % (str_old, str_new))
judge = input('【YES/NO】:')
if judge == 'YES':
file = open(title, 'w')
file.writelines(content)
file.close()
else:
file.close()
这个是不会报错的代码:
title = input('请输入文件名:')
str_old = input('请输入需要替换的单词或字符:')
str_new = input('请输入新的单词或字符:')
count = 0
content = []
file = open(title)
for each in file:
if str_old in each:
count += each.count(str_old)
new = each.replace(str_old, str_new)
content.append(new)
print('文件%s中共有%d个【%s】' % (title, count, str_old))
print('您确定要把所有的【%s】替换为【%s】吗?' % (str_old, str_new))
judge = input('【YES/NO】:')
if judge == 'YES':
file = open(title, 'w')
file.writelines(content)
file.close()
else:
file.close()
两个问题:
1.如果我把
new = file.replace(str_old, str_new)
content.append(new)
这两行放在for循环外面的话,replace语句就会报错,必须要放在for循环里面对each用replace才可以
请问这是for循环的问题吗?
2.我如果想把file.read()的值赋给一个参数或者print(file.read()),只能在for循环之前才能实现,在for循环后面的话就没有值输出
请问这是什么原因呢?
|
|