繁体   English   中英

如何在Python中仅将某些行写入文件?

[英]How do I write only certain lines to a file in Python?

我有一个看起来像这样的文件(必须放在代码框中,使其类似于文件):

text
(starts with parentheses)
         tabbed info
text
(starts with parentheses)
         tabbed info

...repeat

我只想从文件(或每四行)中抓取“文本”行,然后将其复制到另一个文件中。 这是我的代码,但是将所有内容复制到新文件中:

import sys

def process_file(filename):

    output_file = open("data.txt", 'w')

    input_file = open(filename, "r")
    for line in input_file:
        line = line.strip()
                if not line.startswith("(") or line.startswith(""):
                        output_file.write(line)        
    output_file.close()
if __name__ == "__main__":
process_file(sys.argv[1])

您的脚本复制每一行的原因是因为无论哪一line相等, line.startswith("")为True。

您可以尝试使用isspace测试line是否以空格开头:

def process_file(filename):
    with open("data.txt", 'w') as output_file:
        with open(filename, "r") as input_file:
            for line in input_file:
                line=line.rstrip()
                if not line.startswith("(") or line[:1].isspace():
                    output_file.write(line) 
with open('data.txt','w') as of:
    of.write(''.join(textline
                     for textline in open(filename)
                     if textline[0] not in ' \t(')
             )

要写每四行,请使用slice结果[:: 4]

with open('data.txt','w') as of:
    of.write(''.join([textline
                     for textline in open(filename)
                     if textline[0] not in ' \t('][::4])
             )

当我在写操作中使用换行符时,我不需要将其换行。

除了line.startswith("")始终为true之外, line.strip()还将删除前导制表符,从而迫使制表符数据也要写入。 将其更改为line.rstrip()并使用\\t测试选项卡。 您的代码部分应如下所示:

line = line.rstrip()
if not line.startswith(('(', '\t')):
    #....

在评论中回答您的问题:

#edited in response to comments in post
for i, line in input_file:
    if i % 4 == 0:
        output_file.write(line)

尝试:

if not line.startswith("(") and not line.startswith("\t"):

而不做line.strip()(这将删除选项卡)

因此,问题在于(1)您滥用布尔逻辑,并且(2)每行都以“”开头。

首先,布尔逻辑:

or运算符的工作方式是,如果其两个操作数中的任何一个为True,则返回True。 操作数是“ not line.startswith('(')”和“ line.startswith('')”。请注意,此操作数不仅适用于其中一个操作数。如果要将其应用于或的总结果表达式,则必须将整个内容放在括号中。

第二个问题是您使用带零长度强作为参数的startswith()方法。 这实际上是说“匹配前零个字符都不为零的任何字符串。它匹配您可以提供的任何强值。

请参阅其他答案,了解您应该在这里做什么。

暂无
暂无

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

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