相关疑难解决方法(0)

在Python中搜索并替换文件中的一行

我想循环遍历文本文件的内容,并在某些行上进行搜索和替换,并将结果写回文件.我可以先将整个文件加载到内存中然后再写回来,但这可能不是最好的方法.

在以下代码中,最好的方法是什么?

f = open(file)
for line in f:
    if line.contains('foo'):
        newline = line.replace('foo', 'bar')
        # how to write this newline back to the file
Run Code Online (Sandbox Code Playgroud)

python file

271
推荐指数
11
解决办法
42万
查看次数

如何使用Python搜索和替换文件中的文本?

如何使用Python 3搜索和替换文件中的文本?

这是我的代码:

import os
import sys
import fileinput

print ("Text to search for:")
textToSearch = input( "> " )

print ("Text to replace it with:")
textToReplace = input( "> " )

print ("File to perform Search-Replace on:")
fileToSearch  = input( "> " )
#fileToSearch = 'D:\dummy1.txt'

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):
    if textToSearch in line :
        print('Match Found')
    else:
        print('Match Not Found!!')
    tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()


input( '\n\n Press …
Run Code Online (Sandbox Code Playgroud)

python string replace file python-3.x

179
推荐指数
8
解决办法
52万
查看次数

在Python中从大文件中删除行的最快方法

我正在Linux系统上使用一个非常大的(~11GB)文本文件.我正在通过检查文件错误的程序运行它.一旦发现错误,我需要修复该行或完全删除该行.然后重复......

最后,一旦我对这个过程感到满意,我会完全自动完成它.但是现在,让我们假设我正在手动操作.

从这个大文件中删除特定行的最快(在执行时间方面)方法是什么?我想在Python中做到这一点......但是会对其他例子持开放态度.该行可能位于文件中的任何位置.

如果是Python,请假设以下界面:

def removeLine(filename, lineno):

谢谢,

-AJ

python optimization

22
推荐指数
2
解决办法
1万
查看次数

标签 统计

python ×3

file ×2

optimization ×1

python-3.x ×1

replace ×1

string ×1