【问题标题】:Python find, replace or add string in filePython 在文件中查找、替换或添加字符串
【发布时间】:2013-08-09 14:43:04
【问题描述】:

您好,感谢您的关注 :)

我有一个超过 2500 行的文本图块,每行包含有关视频文件的信息。其中一个标签(可以这么说)用于观看状态,我正在寻找一种将其从一个值更改为另一个值的方法,或者如果未设置则添加一个新值。下面的代码有效,但它必须为每个搜索值打开和关闭文件,这意味着它非常慢。任何人都可以建议一种打开文件一次并一次性完成所有搜索的方法吗?

谢谢

for x in y:
    print '    --> ' + x['title'].encode('utf-8')

    searchValue = x['movieid']
    addValue = "\t_w\t1\t"
    checkvalue = "\t_w\t0\t"
    for line in fileinput.input(file, inplace=1):
        if searchValue in line:
            if checkvalue in line:
                line = line.replace(checkvalue, addValue)
            elif not addValue in line:
                line = line + addValue
        sys.stdout.write(line)

这就是我最终的结果,感谢大家的意见。

    myfile_list = open(file).readlines()
    newList = []
    for line in myfile_list:
        for x in y:
            if x['movieid'] in line:
                print '    --> ' + x['title'].encode('utf-8')
                if checkvalue in line:
                    line = line.replace(checkvalue, addValue)
                elif not addValue in line:
                    line = line.replace('\n', addValue+'\n')
        newList.append(line)
    outref = open(file,'w')
    outref.writelines(newList)
    outref.close()

编辑 我遇到了编码问题,文件以 utf-8 编码,但是当搜索值为时出错或找不到匹配项

'Hannibal - S01E01 - Ap\xe9ritif.mkv'

文件中匹配的行看起来像

_F  /share/Storage/NAS/Videos/Tv/Hannibal/Season 01/Hannibal - S01E01 - Apéritif.mkv    _rt 43  _r  8.4 _s  1   _v  c0=h264,f0=24,h0=720,w0=1280    _IT 717ac9d _id 1671    _et Apéritif    _DT 7142d53 _FT 7142d53 _A  4212,4211,2533,4216 _C  T   _G  j|d|h|t _R  GB:TV-MA    _T  Hannibal    _U   thetvdb:259063 imdb:tt2243973  _V  HDTV    _W  4210    _Y  71  _ad 2013-04-04  _e  1   _ai Apéritif    _m  1117

我尝试了 codecs.open 和 decode().encode() 选项,但它总是出错,我相信它是问题所在行中的重音字母,因为它可以在行中执行 if searchValue: 如果该行没有重音字母。这是我目前正在尝试的方法,但我对其他方法持开放态度。

if os.path.isfile("/share/Apps/oversight/index.db"):
    newfile = ""
    #searchValueFix = searchValue.decode('latin-1', 'replace').encode('utf8', 'replace')
    #print searchValueFix
    #print searchValue
    addValue = "\t_w\t1\t"
    replacevalue = "\t_w\t0\t"
    file = open("/share/Apps/oversight/index.db", "r")
    for line in file:
        if searchValue in line:
            if replacevalue in line:
                line = line.replace(replacevalue, addValue)
            elif not addValue in line:
                line = line.replace(searchValue+"\t", searchValue+addValue)
        newfile = newfile + line
    file.close()
    file = open("/share/Apps/oversight/index.db", "w")
    file.write(newfile)
    file.close()
    newfile = ""

【问题讨论】:

  • "r+"而不是"w""r"分别打开文件。然后,您无需打开和关闭它即可读取和写入。

标签: python search encoding replace


【解决方案1】:

类似于 PyNEwbie 提出的方法,可以逐行编写:

myfile_list = open(file).readlines()
outref = open(myfile, 'w')
for line in myfile_list:
    # do something to line
    outref.write(line)

outref.close()

【讨论】:

    【解决方案2】:

    是的,将您的文件读入列表

    myfile_list = open(file).readlines()
    newList = []
    for line in myfile_list:
      .
      .
    
      newList.append(line)   # this is the line after you have made your changes
    outref = open(myfile,'w')
     outref.writelines(newList)
    outref.close()
    

    【讨论】:

    • PyNEwbie,我试过你的方法,但是虽然速度快了很多,但写入的文件和以前一样。我检查了该行确实发生了更改,但没有写入更改?
    • 嗯,这只是意味着您更改的内容在 myfile 列表中没有更改,只是因为我看不到您的代码,所以我将稍微注释一下我的代码 - 如果您发现有用的答案,您应该标记它,如果它被接受的答案,你应该检查它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2013-02-19
    • 2020-08-12
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多