Python:一行中遇到字符如何跳转到下一行

Python: how to go to the next line if you encounter a character within a line

我正在和 Python 做一些 I/O。从文件中读取时,我希望程序忽略该行的其余部分并在遇到分号 (;) 时转到下一行。我有以下代码,但只有当我的行以分号开头而不是分号在行中的其他位置时才有效。请帮助,谢谢。 澄清:然后我想将没有分号的行的每一部分逐行写入一个新文件。基本上我想创建一个新文件,其中没有“;我想忽略这一点”。

def ignoreSemi():
    for line in f:
        for char in line:
            if char == ";":
                line = next(f)

简单地用分号分割行并处理第一部分:

def ignoreSemi():
    for line in f:
        part = line.strip().split(';')
        do_something(part[0])

您可以使用生成器,after_semi 将生成第一个分号之前的部分行

def after_semi(input):
    for line in input:
        yield line.split(';')[0]

with open('output', 'w') as f:
    for line in after_semi(input):
        f.write('%s\n', line)

像这样尝试:会给你没有“;”的行

def ignoreSemi():
    for line in f:
        if ";" not in line:
            # do your stuff

如果遇到;想跳转到下一行:

def ignoreSemi():
for line in f:
    if ";" in line:
        line = next(f)
        # do your stuff

你的问题不是很清楚。你想对分号前的字符做一些有用的事情吗?如果是这样,请考虑使用 line.split(";") 并对返回列表的第一个成员进行操作。如果没有,请尝试使用类似于以下内容的内容:

def ignoreSemi():
    for line in f:
        if ";" not in line:
            [rest of loop here]