【问题标题】:IsADirectoryError: [Errno 21] Is a directory: '.upm'IsADirectoryError:[Errno 21] 是目录:'.upm'
【发布时间】:2021-06-13 09:32:41
【问题描述】:

这是我认为可能发生错误的代码,我已阅读有关消除错误但无法形成代码的帖子。

while True:
    files=os.listdir(".")
    #print(files)
    # Get the MD5 hash for each -- use a for loop to process each file
    for file_name in files:


        with open(file_name , "rb") as fp:


            file_content = fp.read()
            md5 = hashlib.md5(file_content).hexdigest()


        # should we compare the checksums too? XXXXXXXXX


        # check for differences between new scan and old scan.
        if not file_name in baseline.keys():
            # print the name of any new files
        print("new file detected!", file_name)

错误具体是:

Traceback(最近一次调用最后一次):文件“main.py”,第 31 行,在 使用 open(file_name , "rb") as fp: IsADirectoryError: [Errno 21] 是目录:'.upm'

如果有人可以帮助提供正确的代码,那将是非常有帮助的。

【问题讨论】:

  • 错误是说您的当前目录 (".") 有一个 .upm 是一个文件夹。您的问题是在循环listdir 时如何忽略文件夹?
  • 没有 @GinoMempin ,我想使用 os.walk() 传递文件夹和文件。
  • 但无法形成代码。你能帮我吗@GinoMempin。
  • 您的代码中没有os.walk。而且您不能在文件夹上使用open。当你到达一个文件夹时,你需要重复循环遍历该文件夹的每个文件。
  • stackoverflow.com/questions/52338706/… 。在这篇文章中,他们建议使用 os.walk() @GinoMempin

标签: python-3.x


【解决方案1】:

我想知道@jaychandra 的答案如何是完整的答案,而它不会检查子文件夹中的文件,如果您只想比较文件名,也没有散列文件的意义。

files=os.listdir(".")
for root, dirs, files in os.walk('.'):
    for file_ in files:
        with open(os.path.join(root, file_) , "rb") as fp:
            file_content = fp.read()
            md5 = hashlib.md5(file_content).hexdigest()

        if not md5 in baseline.keys():
            print("new file detected or file has been changed!", file_)

我所做的是,它还将散列所有子文件夹中的所有文件。并检查是否添加了新文件或更改了以前的文件。

【讨论】:

    【解决方案2】:

    您正在将文件夹或目录作为文件打开,这会导致该错误。 可以通过将files=os.listdir(".") 替换为files = [i for i in os.listdir() if os.path.isfile(i)] 来修复它。这将消除该错误。

    while True:
        files=[i for i in os.listdir() if os.path.isfile(i)]
        #print(files)
        # Get the MD5 hash for each -- use a for loop to process each file
        for file_name in files:
    
    
            with open(file_name , "rb") as fp:
    
    
                file_content = fp.read()
                md5 = hashlib.md5(file_content).hexdigest()
    
    
            # should we compare the checksums too? XXXXXXXXX
    
    
            # check for differences between new scan and old scan.
            if not file_name in baseline.keys():
                # print the name of any new files
            print("new file detected!", file_name)
    

    【讨论】:

      猜你喜欢
      • 2018-06-20
      • 2022-12-07
      • 1970-01-01
      • 2020-11-20
      • 2022-08-22
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      相关资源
      最近更新 更多