[英]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.