Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何迭代循环_Python - Fatal编程技术网

Python 如何迭代循环

Python 如何迭代循环,python,Python,我编写这段代码是为了遍历文件0-100。问题是,当未找到日志文件0时,它不会转到下一个文件 我尝试使用返回I+1,但由于我不熟悉编码,不知道如何继续,因此无法使用。如何忽略空文件并继续下一步。我应该留个柜台吗 import os path = "C:\\Users\\Bindu\\Documents\\Thesis\\lfiles\\" list = os.listdir(path) # dir is your directory path number_files = len(list)

我编写这段代码是为了遍历文件0-100。问题是,当未找到日志文件0时,它不会转到下一个文件

我尝试使用
返回I+1
,但由于我不熟悉编码,不知道如何继续,因此无法使用。如何忽略空文件并继续下一步。我应该留个柜台吗

import os

path = "C:\\Users\\Bindu\\Documents\\Thesis\\lfiles\\"

list = os.listdir(path)  # dir is your directory path
number_files = len(list)
print(number_files)
try:
      for i in range(0, 100):
        path2 = "data." + str(i) + "\\Log." + str(i)
        file = path + path2

        f = open(file)
        if not os.path.exists(path2):
            with open(path2) as fi:
                if not fi.read(3):  # avoid reading entire file.
                    print("File is empty")

except Exception as e:
     raise SystemExit("File empty")

不要在except块中使用SystemExit(“File Empty”),而是使用print(“File Empty”)。

不要在except块中使用SystemExit(“File Empty”),而是使用print(“File Empty”)。

您的代码在不需要的情况下循环通过
0
100
。 您的代码应该如下所示:

import os
import traceback

path = "C:\\Users\\Bindu\\Documents\\Thesis\\lfiles\\"

try:
      for file in os.listdir(path):
        file = path + file

        f = open(file)
        with open(path2) as fi:
            if not fi.read(3):  # avoid reading entire file.
                print("File is empty")

except Exception as e:
     print(traceback.format_exc())
以及
listdir
上的注释:

listdir(path)返回一个列表,其中包含 路径指定的目录。列表的顺序是任意的。是的 不包括特殊条目“.”和“..”,即使它们存在 在目录中


因此
type(os.listdir('.')
将给出
,您可以迭代结果。

您的代码在
0
100
之间循环,而这并不是必需的。 您的代码应该如下所示:

import os
import traceback

path = "C:\\Users\\Bindu\\Documents\\Thesis\\lfiles\\"

try:
      for file in os.listdir(path):
        file = path + file

        f = open(file)
        with open(path2) as fi:
            if not fi.read(3):  # avoid reading entire file.
                print("File is empty")

except Exception as e:
     print(traceback.format_exc())
以及
listdir
上的注释:

listdir(path)返回一个列表,其中包含 路径指定的目录。列表的顺序是任意的。是的 不包括特殊条目“.”和“..”,即使它们存在 在目录中


因此
type(os.listdir('.')
将给出
,您可以对结果进行迭代。

为什么不对os.listdir(path)中的文件使用
?这样,您就不会遇到试图读取不存在的文件的问题。
列表也是一个关键字,因此我建议不要将其用作变量名。为什么不在os.listdir(路径)中为文件使用
?这样,您就不会遇到试图读取不存在的文件的问题。
列表也是一个关键字,因此我建议不要将其用作变量名。