简体   繁体   English

Python:读取文件并排除具有某些字符的行

[英]Python: reading a file and excluding lines with certain characters

I am trying to figure out how to write a function that opens a file and reads it, however I need it to ignore any lines that contain the character '-'我想弄清楚如何编写一个打开文件并读取它的函数,但是我需要它来忽略包含字符 '-' 的任何行

This is what I have so far:这是我到目前为止所拥有的:

def read_from_file(filename):
    with open('filename', 'r') as file:
        content = file.readlines()

Any help would be appreciated任何帮助,将不胜感激

Filter out character '-'-containing lines from your read-in lines:从读入行中过滤掉包含字符“-”的行:

filtered_lines = [x for x in content if '-' not in x]

I'd filter out while reading the file, not collect the unwanted lines in the first place.我会在读取文件时过滤掉,而不是首先收集不需要的行。

def read_from_file(filename):
    with open(filename) as file:
        content = [line for line in file if '-' not in line]

Also note that the 'filename' in your open('filename', 'r') is wrong and that the 'r' is unnecessary, so I fixed/removed that.另请注意,您的open('filename', 'r') 'filename'的“文件名”是错误的,并且'r'是不必要的,因此我修复/删除了它。

Gwang-Jin Kim and Heap Overflow answers are both 100% right, but, I always feel that using the tools that Python give you to be a plus one, so here is a solution using the built-in filter() function: Gwang-Jin Kim 和 Heap Overflow 的答案都是 100% 正确的,但是,我总觉得使用 Python 给你的工具是一个加分项,所以这里有一个使用内置filter()函数的解决方案:

list(filter(lambda line: "-" not in line, file.splitlines()))

def read_from_file(filename):
    with open(filename, "r") as file:
        content = filter(lambda line: "-" not in line, file.readlines())

    return list(content)

Here is a more verbose, yet more efficient solution:这是一个更详细但更有效的解决方案:

def read_from_file(filename):

    content = []
    with open(filename, "r") as file:
        for line in file:
            if "-" not in line:
                content.append(line)

    return content

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

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