python 文件编码问题导致文件不能写入
写了一个代码,实现的功能是:对于文件a.txt中某字段在b.txt中有,则返回a.txt中这行数据,并保存到新的文件。但是貌似文件编码原因,数据无法写入,烦请大侠帮忙看看...
写了一个代码,实现的功能是:对于文件a.txt中某字段在b.txt中有,则返回a.txt中这行数据,并保存到新的文件。但是貌似文件编码原因,数据无法写入,烦请大侠帮忙看看
def include(a,b,c):
import re
import codecs
in_put=open(a)
out_put=open(b,'w')
include=open(c)
line=in_put.readlines()
include_line=include.readlines()
include_list=[]
for i in include_line:
result=re.sub(r'\n','',i)
include_list.append(i)
for i in line
contract_no=re.search(r'contract_no=(\d+)',i)
if contract_no:
if contract_no.group(1) in include_list:
out_put.write(i)
in_put.close()
include.close()
out_put.close() 展开
def include(a,b,c):
import re
import codecs
in_put=open(a)
out_put=open(b,'w')
include=open(c)
line=in_put.readlines()
include_line=include.readlines()
include_list=[]
for i in include_line:
result=re.sub(r'\n','',i)
include_list.append(i)
for i in line
contract_no=re.search(r'contract_no=(\d+)',i)
if contract_no:
if contract_no.group(1) in include_list:
out_put.write(i)
in_put.close()
include.close()
out_put.close() 展开
1个回答
展开全部
# adjust your code like:
def include(a,b,c):
import re
# import codecs # unusage
in_put=open(a)
out_put=open(b,'w')
inc_handle = open(c) # include=open(c) the "include" is a function or var?
line=in_put.readlines()
include_line=inc_handle.readlines()
include_list=[]
for i in include_line:
result=re.sub(r'\n','',i)
include_list.append(result) # remove line ended char?
# or remove not digital char?
for i in line: # lost ":" at line end
contract_no=re.search(r'contract_no=(\d+)',i)
if contract_no:
if contract_no.group(1) in include_list:
out_put.write(i)
in_put.close()
inc_handle.close()
out_put.close()
or more pythonic:
def include(a,b,c):
import re
with open(c) as handle:
inc = re.findall(r'\d+', handle.read())
with open(b,'w') as ostream, open(a) as istream:
for i in istream:
contract_no = re.search(r'contract_no=(\d+)',i)
if contract_no and contract_no.group(1) in inc:
ostream.write(i)
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询