Python 的搜索和替换如何处理文件编辑中的可变文本长度?
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中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Linux终端中查看Python版本时遇到权限问题的解决方法当你在Linux终端中尝试查看Python的版本时,输入python...

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

在使用Python的pandas库时,如何在两个结构不同的DataFrame之间进行整列复制是一个常见的问题。假设我们有两个Dat...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

Uvicorn是如何持续监听HTTP请求的?Uvicorn是一个基于ASGI的轻量级Web服务器,其核心功能之一便是监听HTTP请求并进�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...
