简体   繁体   English

Python,将关键字之间的txt行附加到另一个txt

[英]Python, append txt lines between keywords to another txt

Not an experienced user here. 这里不是经验丰富的用户。

I have a text file (export.txt) that goes: 我有一个文本文件(export.txt),该文件为:

*NODE
several thousand lines like this one
several thousand lines like this one
several thousand lines like this one
*ANY OTHETR WORD

I want to copy the lines between these two keywords (both unfortunatly starting with "*") to the end of another file (original.txt). 我想将这两个关键字之间的行(都不幸地以“ *”开头)复制到另一个文件(original.txt)的末尾。

Tried this solution but am getting an error when trying to copy the data: 尝试过此解决方案,但在尝试复制数据时遇到错误:

* * * "Traceback (most recent call last):
File "myscript.py", line 28, in <module>
for line in f:
File "/opt/ansa_15.2.3/meta_post_v15.2.3/../shared_v15.2.3/python/linux64/lib/python3.3/codecs.py",
line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd3 in position 267: invalid continuation byte"
* * *

May ask for a solution? 可能要求解决方案? Thanks! 谢谢!

http://docs.python.org/howto/unicode.html#the-unicode-type http://docs.python.org/howto/unicode.html#the-unicode-type

str = unicode(str, errors='replace')

OR 要么

str = unicode(str, errors='ignore')

Note : This solution will strip out (ignore) the characters in question returning the string without them. 注意 :此解决方案将删除(忽略)有问题的字符,返回不包含这些字符的字符串。 Only use this if your need is to strip them not convert them. 仅当您需要剥离它们而不转换它们时才使用此方法。

Alternatively, use the open method from the codecs module to read in the file: 或者,使用编解码器模块中的open方法读取文件:

import codecs
with codecs.open(file_name, "r",encoding='utf-8', errors='ignore') as fdata:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM