跟踪文件处理:错误:找不到文件

时间:2018-04-07 20:39:06

标签: python python-3.x

我试图读取特定文件夹中的所有文件,然后读取每个文件的第一行,创建一个列表,然后将其与现有列表进行匹配。

下面是代码和输出看起来像我的第一个循环实例正常,然后它抛出某种错误:

import os
import sys
import bz2
import glob

# f = open('C:\\Users\sauris\Desktop\pyfile\out1.txt', 'w')
# sys.stdout = f

path = 'C://Users/sauris/Desktop/pyfile/folder-test'

for filename in os.listdir(path):
    try:
        print('Checking file-', filename)
        handle = bz2.BZ2File(filename, 'rb')
        # print(name)
        # handle = bz2.BZ2File(name, 'rb'
    except:
        raise
        print('no files found')

lst2 = ['But', 'soft', 'what', 'light', 'through', 'yonder', 'window', 'breaks']
firstline = (handle.readline().decode()).rstrip()

st = (firstline.split(' '))

if st == lst2:
    print('Header Validation: OK')
    print('Column Values are Same And In Order')
elif set(st) == set(lst2):
    print('Header Validation: NOT OK')
    print('Headers Are Same But Not In Order')
else:
    print('Header Validation: NOT OK')
    print('Headers Are Different Also Not In Order')

if len(st)==len(lst2):
    print('Number Of Column :OK')
else:
    print('Number Of Column:NOT OK')

handle.close()

输出:

C:\Users\sauris\Desktop\pyfile>folder-read.py

Checking file- sampledatafile.txt.bz2
Header Validation: OK
Column Values are Same And In Order
Number Of Column :OK
Checking file- sampledatafile2.txt.bz2

Traceback (most recent call last):
File "C:\Users\sauris\Desktop\pyfile\folder-read.py", line 13, in <module>
File "C:\Users\sauris\AppData\Local\Programs\Python\Python36-32\lib\bz2.py", l
ine 96, in __init__
self._fp = _builtin_open(filename, mode)
FileNotFoundError: [Errno 2] No such file or directory: 'sampledatafile2.txt.bz2'

1 个答案:

答案 0 :(得分:1)

尝试:

bz2.BZ2File(os.path.join(path,filename),'rb')

而不是bz2.BZ2File(filename, 'rb')。我认为您唯一的问题是您没有正确添加路径。