python - fileinput.Fileinput .read() 整个文件的函数

标签 python file-io replace

在 fileinput.Fileinput (或其他模块/类)中是否有一种方法可以将整个文件读入内存,以便我可以用列表中的文本 block 替换文件中的文本 block (保存在内存)。

有一个 .readline 函数,但我需要查找并替换文本 block ,并且我不希望在压缩文件的同时逐行压缩文本 block 。

最佳答案

是的,file对象有一个read方法,可以将整个文件内容读入内存。

with open("myfile.txt") as infile:
    text = infile.read()

# manipulate text here

with open("myfile.txt", "w") as outfile:
    outfile.write(text)

关于python - fileinput.Fileinput .read() 整个文件的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36750576/

相关文章:

python - lxml.html.tostring 在打印时重新排序了 doctype 和 xml 标签

python - 在 astropy 表的 numpy 数组中转换一个 astropy 表列表

python - 获取 ttf/otf 字体本地化名称

c++ - 程序复制文件与使用 ShellExecute 和 cp 之间的权衡是什么?

css - 有没有办法使文件输入上的 native `browse` 按钮更大跨浏览器?

file-io - 从文件加载图像并设置到 UnityEngine.UI.Image Unity

vim - 文本替换文件数量

python - 将 Sympy 与 Pypy 结合使用

regex - VIM:替换没有参数的函数调用

python - Pandas :替换字符串中的子字符串