写for语句的结果

write result of for statement

我是 Python 的新手,尝试执行以下操作

到目前为止,我得到了以下信息,我知道某处应该有一个 o.write,但是我尝试了很多不同的地方,但似乎没有任何效果,我很确定我缺少一些简单的东西。

import os

i = open("input.txt", "r+")
o = open("output.txt", "a+")

for line in i.readlines():
    (line.replace(" ", "\n"))
    if ":" in line:
        (line)


i.close()
o.close()

输入文件如下

192.168.1.1 192.168.2.1 192.168.3.1 2001:0db8:85a3:0000:0000:8a2e:0370:7334

您可以先构建新的文件内容,然后再写入:

import os

i = open("in", "r+")
o = open("out", "a+")

result = ""

for line in i.readlines():
        if ":" not in line:
                result += line.replace(" ", "\n")


o.write(result)

i.close()
o.close()

所以我有:

EDITED 删除带有 :

的行

test.txt

192.168.1.1 192.168.2.1 192.168.3.1 2001:0db8:85a3:0000:0000:8a2e:0370:7334

answer.py

with open('test.txt', 'r') as f:
    text = f.read()

lines = text.split(' ')
lines = [line for line in lines if ':' not in line]

with open('result.txt', 'w') as f:
    f.write('\n'.join(lines))

result.txt

192.168.1.1
192.168.2.1
192.168.3.1

这是你想要的吗?

  • 在 遍历文件内容之前用换行符替换空格 。如果你不这样做,那么你只会迭代一行。

  • 您的代码中不需要 os 库。

  • 测试行是否没有冒号(:)后调用o.write(line)

  • 使用上下文管理器执行您的 I/O 操作。

  • 使用比 io 更具描述性的名称,以避免编写混乱的代码。

经过以上修改,您的代码变为:

with open("input.txt", "r+") as infile, open("output.txt", "a+") as outfile:
    contents = infile.read().replace(' ', '\n')
    for line in contents.split('\n'):
        if ':' not in line:
            outfile.write(line + '\n')