Python在fi中查找、替换或添加字符串

2024-04-30 04:21:53 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,感谢您的关注:)

我有一个超过2500行的文本平铺,每行都包含一个视频文件的信息。其中一个标签(可以说)是监视状态,我正在寻找一种方法,将其从一个值更改为另一个值,或者在未设置的情况下添加一个新值。下面的代码可以工作,但是它必须为每个searchvalue打开和关闭文件,这意味着它非常慢。有谁能建议一种方法打开一次文件,然后一次完成所有的搜索?在

谢谢

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)

这就是我最后的结论,感谢大家的投入。在

^{pr2}$

编辑 我遇到了一个编码问题,该文件是用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

我试过了编解码器.打开和decode().encode()选项,但它总是会出错,我相信这是一行中的重音字母,因为它可以做if searchValue in line:如果行没有重音字母。这是我目前正在尝试的,但我对其他方法持开放态度。在

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 = ""

Tags: 文件方法inshareforiflinereplace
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提出的方法类似,您可以将第1行写成1行:

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

outref.close()

相关问题 更多 >