Python 檔案搜尋並替換為不同的文字長度
在嘗試使用Python 3 在檔案中執行搜尋和取代時,某些使用者當替換文字比原始文字短或長時會遇到問題。這可能會導致將意外的字元新增至檔案。
請考慮提供的程式碼:
# Get user input for search and replacement text textToSearch, textToReplace, fileToSearch = input("Text to search for: "), input("Text to replace it with: "), input("File to perform Search-Replace on: ") # Open the file and loop through each line with open(fileToSearch, 'r+') as tempFile: for line in fileinput.input(fileToSearch): # Perform replacement only when a match is found if textToSearch in line: line = line.replace(textToSearch, textToReplace) # Write the modified line back to the file tempFile.write(line)
但是,當用較短的文字取代較長的文字時,此方法會失敗,因為剩餘的字元
解:
到為了解決這個問題,建議將整個文件讀入內存,執行搜尋和替換操作,然後將修改的內容分步寫回到文件中:
# Read the file into memory with open('file.txt', 'r') as file: filedata = file.read() # Perform the replacement filedata = filedata.replace('abcd', 'ram') # Write the modified content back to the file with open('file.txt', 'w') as file: file.write(filedata)
此方法可確保文件已就地修改,不會引入任何意外字元。
以上是Python 的搜尋和取代如何處理文件編輯中的可變文字長度?的詳細內容。更多資訊請關注PHP中文網其他相關文章!