![](/img/trans.png)
[英]import a txt file in python and print all lines with specific word in string
[英]Filter txt lines that start with a specific string (Python)
我有一个看起来像这样的 txt 文件:
...
|J150|DRE.16.2|T|2|DRE.16|PROVISAO P CSLL|6779,24|D|D||
|J150|DRE.16.2.001|D|3|DRE.16.2|CSLL|6779,24|D|D||
|J150|DRE.17|T|1||LUCRO DO EXERCICIO|55797,1|C|R||
|J005|01012018|31122018|1||
|J100|BP.01|T|1||A|ATIVO|5540527,48|D|8656252,32|D||
|J100|BP.01.1|T|2|BP.01|A|ATIVO CIRCULANTE|5030370,68|D|7881200,94|D||
|J100|BP.01.1.1|T|3|BP.01.1|A|DISPONIBILIDADES|380741,7|D|777224,63|D||
|J100|BP.01.1.1.01|T|4|BP.01.1.1|A|CAIXA|96786,62|D|69935,41|D||
|J100|BP.01.1.1.01.001|D|5|BP.01.1.1.01|A|Caixa|96786,62|D|69935,41|D||
...
它很长。 我想在一个新文件中只分离以“|J100|”开头的行。 我在这里尝试了一些答案,但在我的情况下不起作用。 在我的试验下面:
path="file.txt"
open('newfile','w').writelines([ line for line in open(path) if '|J100|' in line])
没用,得到UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 255: invalid start byte
然后我尝试了这个:
with open(path,'rb') as f,open('new.txt','wb') as g:
g.writelines(filter(lambda line: '|J100|' in line, f))
并得到这个作为响应: TypeError: a bytes-like object is required, not 'str'
有任何想法吗?
如果
path="file.txt"
open('newfile','w').writelines([ line for line in open(path) if '|J100|' in line])
引发UnicodeDecodeError
然后 file.text 的内容未编码为 UTF-8。
这段代码
with open(path,'rb') as f,open('new.txt','wb') as g:
g.writelines(filter(lambda line: '|J100|' in line, f))
引发TypeError
因为您正在以二进制模式读取文件,因此其内容为 output 作为bytes ,但 lambda 将这些字节与字符串值( '|J100|'
)进行比较。 最好的方法是将字节与字节( b'|J100|'
)进行比较。 此外,如果您只想要以特定值开头的行,请使用bytes.startswith过滤包含 |J100| 的行。 开始后:
with open(path,'rb') as f,open('new.txt','wb') as g:
g.writelines(filter(lambda line: line.startswith(b'|J100|'), f))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.