簡體   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