我在读取多个 txt 文件时遇到问题

I am having problems reading multiple txt files

我在尝试读取 python 中的多个文本文件时遇到了问题。 我试图只从文本文件中获取 IP 地址。当我尝试使用单个文本文件时,它工作正常。但是,当我复制多个文本文件到文件夹时,我只得到第一个文件的输出。

import os
import re
import glob



path = "file_direction"
pattern = re.compile(r'(?:(?:1\d\d|2[0-5][0-5]|2[0-4]\d|0?[1-9]\d|0?0?\d)\.){3}(?:1\d\d|2[0-5][0-5]|2[0-4]\d|0?[1-9]\d|0?0?\d)')
valid = []
invalid = []



for path in glob.glob(os.path.join(path, "*.txt")):
    with open(path, mode="r", encoding="utf-8") as fh:
        string = fh.readlines()


for line in string:
    line = line.rstrip()
    result = pattern.search(line)

    # valid IP addresses
    if result:
        valid.append(line)

    # invalid IP addresses
    else:
        invalid.append(line)

# displaying the IP addresses
print("Valid IPs")
print(valid)
print("Invalid IPs")
print(invalid)

您的缩进有问题,您当前的代码仅在最后一个文件上运行。

正确代码:

import os
import re
import glob

path = "file_direction"
pattern = re.compile(r'(?:(?:1\d\d|2[0-5][0-5]|2[0-4]\d|0?[1-9]\d|0?0?\d)\.){3}(?:1\d\d|2[0-5][0-5]|2[0-4]\d|0?[1-9]\d|0?0?\d)')
valid = []
invalid = []

for path in glob.glob(os.path.join(path, "*.txt")):
    with open(path, mode="r", encoding="utf-8") as fh:
        string = fh.readlines()

    for line in string:
        line = line.rstrip()
        result = pattern.search(line)

        # valid IP addresses
        if result:
            valid.append(line)

        # invalid IP addresses
        else:
            invalid.append(line)

# displaying the IP addresses
print("Valid IPs")
print(valid)
print("Invalid IPs")
print(invalid)