嗨,感谢您的关注:)
我有一个超过 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 in line: if the line does not have一个重音字母。这是我目前正在尝试的,但我对其他方法持开放态度。
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 = ""