|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
def file_replace():
file_name = input('请输入文件名:')
file = open(file_name,'r+')
old_word = input('请输入要替换的单词或字符:')
new_word = input('请输入新的单词或字符:')
count = 0
count = file.read().count(old_word)
print('文件'+file_name+'中共有%d个%s' %(count, old_word))
print('您确定要把所有的【%s】替换为【%s】吗?' % (old_word, new_word))
order = input('【YES/NO】:')
#print('order is %s' % order)
if order == 'YES' or order == 'yes':
content = []
for each_line in file:
print('under command')#加打印看是不是进入到了for循环
if old_word in each_line:
each_line = each_line.replace(old_word, new_word)
content.append[each_line]
#print('debug')
print(content)#打印下看content里面都是些什么东东
#file.close()
file = open(file_name,'r+')
file.writelines(content)#将修改后的内容写入文件
for each_line in file.readlines():#打印文件内容看看是否修改成功
print(each_line,end='')
file.close()
file_replace()
这是小弟编写的将文件中某个字替换并打印出新文件的字符,想着是想打开文件,然后查找并打印出要替换的字有多少个,并提示用户是否确定修改,如果确定 的话,修改后打印,如果不替换,直接关闭文件。但是疑惑是为什么替换部分的for循环没有执行,没进入循环。在idle中用简短的代码试了下,是可以的,代码如图片所示,和文件中的代码逻辑一样。
请大家帮忙看看,谢谢。
|
-
|