IOError:[Errno 2]用于解析txt文件的Python脚本

2024-04-20 11:29:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在启动一个python脚本来解析文件夹中的一些小文本文件。我需要检索总是不同的特定信息(在本例中是主机名、Cisco交换机的型号和序列号),因此不能使用正则表达式。不过,我可以很容易地找到包含信息的行。到目前为止,我的情况是:

import os

def parse_files(path):
    for filename in os.listdir(path):
        with open(filename,'r').read() as showfile:
            for line in showfile:
                if '#sh' in line:
                    hostname = line.split('#')[0]
                if 'Model Number' in line:
                    model = line.split()[-1]
                if 'System serial number' in line:
                    serial = line.split()[-1]
        showfile.close()

path = raw_input("Please specify Show Files directory: ")

parse_files(path)

print hostname,model,serial

然而,这又回来了:

Traceback (most recent call last):
  File "inventory.py", line 17, in <module>
    parse_files(path)
  File "inventory.py", line 5, in parse_files
    with open(filename,'r').read() as showfile:
IOError: [Errno 2] No such file or directory: 'Switch01-run.txt'

开关01在哪里-运行.txt'是指定文件夹中的文件。我不知道我在哪里拐错了弯。你知道吗


Tags: pathin文件夹信息forifparseos
1条回答
网友
1楼 · 发布于 2024-04-20 11:29:36

问题是os.listdir()返回的是目录中的文件名,而不是文件的完整路径。你知道吗

您需要这样做:

with open(os.path.join(path,filename),'r') as showfile:

这修复了两个问题-IOerror和尝试从字符串中读取行时会遇到的错误。你知道吗

相关问题 更多 >