[英]Replacing text in Python 3 but its reading only one line
我正在尝试使用搜索并在Python 3中用文件替换
但是当我尝试我的代码时,它仅在第一行起作用,而不是遍历每一行并替换它。
到目前为止我正在尝试
f1 = open('test.txt', 'r')
f2 = open('test2.txt', 'w')
for line in f1:
f1.readlines()
find = (input('Enter word to find: '))
while find in line:
print('Word Found')
replace = input('Enter Word to replace with: ')
replace_action = (input('Are you sure you want to replace Y or N:'))
if replace_action.lower() == 'y':
f2.write(line.replace(find.lower(), replace))
else:
print('You have cancelled this operation')
else:
print('Word not found in file')
f1.close()
f2.close()
这段代码仅读取第一行,而不再起作用。
发生这种情况是因为您没有正确读取文件。
for line in f1:
f1.readlines()
f1.readlines()消耗所有文件行,并返回字符串列表。
您只需要删除f1.readlines()行。
如果您想了解以python读取文件的各种方式,请查阅文档。 https://docs.python.org/2.7/tutorial/inputoutput.html
https://docs.python.org/3/tutorial/inputoutput.html
f1 = open('test.txt', 'r')
f2 = open('test2.txt', 'w')
lines = f1.readlines()
find = (input('Enter word to find: '))
replace = input('Enter Word to replace with: ')
for line in lines:
print('current line: {}'.format(line))
if not find in line:
print('world {} not found in this line. Moving to next line'.format(find))
continue
print('World {} found in this line'.format(find))
replace_action = input('Are you sure you want to replace for this line y or n')
if replace_action.lower() == 'y':
line = line.replace(find.lower(), replace)
f2.write(line)
print("New line: {}".format(line))
else:
print('You have cancelled this operation')
print("")
f1.close()
f2.close()
该方法readlines()
读取直到EOF使用readline()
并返回包含行的列表。
f1 = open('test.txt', 'r')
f2 = open('test2.txt', 'w')
f1_lines = f1.readlines()
f1.close()
for line in f1_lines:
find = input('Enter word to find: ')
if find in line:
print('Word Found')
replace = input('Enter Word to replace with: ')
replace_action = input('Are you sure you want to replace Y or N:')
if replace_action.lower() == 'y':
f2.write(line.replace(find.lower(), replace))
else:
print('You have cancelled this operation')
else:
print('Word not found in file')
f2.write(line)
f2.close()
根据对问题的了解,我改变了一些想法。 if find in line
检查您要查找的输入是否在行中。 如果是,则使用替换将行写入f2,否则将行直接写入f2。
编辑:我猜你还有另一个问题。 为我工作。
runfile('C:/Users/mathieu.scheltienne/Desktop/test/untitled0.py', wdir='C:/Users/mathieu.scheltienne/Desktop/test')
Enter word to find: hello
Word Found
Enter Word to replace with: good bye
Are you sure you want to replace Y or N:y
Enter word to find: hello
Word Found
Enter Word to replace with: good bye
Are you sure you want to replace Y or N:y
Enter word to find: hello
Word Found
Enter Word to replace with: good bye
Are you sure you want to replace Y or N:y
输入文件为:test.txt
hello world
hello galaxy
hello universe
输出文件:
good bye world
good bye galaxy
good bye universe
仅包含一个单词的版本,每行仅将替换为一个单词:
f1 = open('test.txt', 'r')
f2 = open('test2.txt', 'w')
f1_lines = f1.readlines()
f1.close()
find = input('Enter word to find: ')
replace = input('Enter Word to replace with: ')
counter = 0
for line in f1_lines:
if find in line:
print('Word Found')
f2.write(line.replace(find.lower(), replace))
counter += 1
else:
f2.write(line)
if counter == 0:
print('Word not found in file')
else:
print('{} words replaced'.format(counter))
f2.close()
我认为您已经有了解决方案,但是很少有地方可以优化它。
with
处理文件,那么您不必担心关闭它。 在您的情况下,如果在for循环期间抛出异常,则不会关闭文件。 with
您一起使用不需要调用readline()
。 try/catch
块。 这是另一种方法。
def readfile_and_replace(input_filename, output_filename):
#using python context manager to open file. File will be closed even in case of exception
with open(input_filename) as input_file:
with open(output_filename,'w') as output_file:
try:
for line in input_file:
search_str = (input('Enter word to find: '))
new_line = line
if search_str in line:
replace_str = input('Enter Word to replace with: ')
if input('Are you sure you want to replace Y or N:').upper() == 'Y':
new_line = line.replace(search_str.lower(), replace_str)
#print(line.replace(search_str.lower(), replace_str))
else:
print('You have cancelled this operation')
else :
print('Word not found in current line')
output_file.write(new_line)
except KeyboardInterrupt:
print("user aborted the program")
readfile_and_replace(input_filename='logs.txt', output_filename='logs2.txt')
希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.