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中文网其他相关文章!