如何在Python中只向文件写入某些行?

2024-05-29 09:50:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像这样的文件(必须放在代码框中以便它类似于文件):

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

...repeat

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

^{pr2}$

Tags: 文件代码text文本info内容withtabbed
3条回答
with open('data.txt','w') as of:
    of.write(''.join(textline
                     for textline in open(filename)
                     if textline[0] not in ' \t(')
             )

要每四行写入一次,请使用slice result[::4]

^{pr2}$

当我在write中使用新行时,我不需要重新输入新行。在

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

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

针对您在评论中提出的问题:

^{pr2}$

脚本复制每一行的原因是因为line.startswith("")是真的,不管line等于什么。在

您可以尝试使用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) 

相关问题 更多 >

    热门问题