为什么当扩展变量为一时我的代码会崩溃

问题描述 投票:0回答:1

我正在为文件分类器编写代码,遇到这样的问题:当扩展变量只有 1 时,代码就会冻结,我试图获得像 print("hall") 这样的基本响应,但这在检查 len 后不起作用扩展名我更困惑了,因为它清楚地显示了 1 所以请帮忙

请参阅上面我尝试过的内容,我现在期望跳过该扩展,然后继续处理文件夹中的其他文件

import os
foldername=input("name of folder: ")


path=os.listdir(foldername)

with open("C:/Users/flori/OneDrive/Dokumente/code/extesions.txt","r") as f:
   
        k=f.read()
        

n=0
while len(path)!=n:
    #getting the extension from the file to sort it in the folders
    extension=path[n].split(".")
    print(len(extension))
    print(extension)
    #looking if the extesion is matching with any registerd extesion in the file "k"
    
    
    
    
    ü=0
    b=0
    with open("C:/Users/flori/OneDrive/Dokumente/code/extesions.txt","r") as f:
                
                 k=f.readlines()  

        
    while b < len(k):
          
         if len(extension)==2:
            
            for i in k:
                print(len(k)-1)
                






               
                
                print(len(extension))

                if extension[1]==k[b][:-1]:
                    print("match")
                    


                print(k[b])
                b=b+1
         
                
    
    
    
    
    
            ü=ü+1
         else:
             path[+1]
    n=n+1
    "/n"
    "/n"
    "/n"
python variable-assignment file-sorting code-freeze
1个回答
0
投票

path[+1]
部分,它似乎试图增加路径的索引,但您没有更新
n
,因此您陷入了无限循环。增加循环计数器的正确方法是
n += 1

字符串“/n”不会打印换行符。要打印换行符,您应该使用

print("\n")

您正在读取扩展文件两次。一次读完整个内容,然后逐行读。这是多余的。

使用 for 循环来遍历路径中的每个文件比 while 循环更Pythonic。

我尝试解决这些问题如下:


import ios

foldername = input("name of folder: ")
path = os.listdir(foldername)

# Just read the extensions once and store them in a list
with open("C:/Users/flori/OneDrive/Dokumente/code/extesions.txt", "r") as f:
    extensions_list = [line.strip() for line in f.readlines()]

for filename in path:
    # Getting the extension from the file to sort it in the folders
    extension = filename.split(".")
    print(len(extension))
    print(extension)

    # If file has no extension or is a hidden file (starts with dot)
    if len(extension) < 2:
        print("Skipping file with no extension or hidden file.")
        print("\n")
        continue

    for known_extension in extensions_list:
        if extension[1] == known_extension:
            print("match")
            print(known_extension)
            break
    else:
        print("No match found for this extension.")
    
    print("\n")

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.