Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.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_File_Directory - Fatal编程技术网

在python中迭代大型文件目录系统,获取太多的值以进行解压缩

在python中迭代大型文件目录系统,获取太多的值以进行解压缩,python,file,directory,Python,File,Directory,我正在用python迭代一个非常大的文件和目录系统。我从基本目录开始,我知道该目录的深度不超过1个文件夹,超过了基本目录。我正在尝试读取base_directories children文件夹中每个文件的第二行,代码如下: a_list = [] for dir, files in os.walk(base_directory): for file in files: f=open(file, 'r') for line in f: #read

我正在用python迭代一个非常大的文件和目录系统。我从基本目录开始,我知道该目录的深度不超过1个文件夹,超过了基本目录。我正在尝试读取base_directories children文件夹中每个文件的第二行,代码如下:

a_list = []
  for dir, files in os.walk(base_directory):
    for file in files:
      f=open(file, 'r')
      for line in f:
        #reads in the second line
        if line==1:
          a_list.append(line)
          break
      f.close() 

但是我得到了太多的值,无法专门在这行“for dir,file in os.walk(base_directory)”中解包,谢谢您的帮助

您应该解包一个3元组

walk(top, topdown=True, onerror=None, followlinks=False) Directory tree generator. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple dirpath, dirnames, filenames 而且,这也行不通<代码>行是一个字符串

  for line in f:
    #reads in the second line
    if line==1:
      a_list.append(line)
      break
你可以把它改成这样

  for i, line in enumerate(f):
    #reads in the second line
    if i==1:
      a_list.append(line)
      break
但我认为这是一个更简单的方法

  import os
  a_list = []
  for dirpath, dirnames, files in os.walk(base_directory):
    for file in files:
      with open(os.path.join(dirpath, file), 'r') as f:
        next(f)                 # skip the first line
        a_list.append(next(f))  # store the second line

谢谢你,伙计。很抱歉,如果这是一个简单的问题,但我对python还是相当陌生的。
  import os
  a_list = []
  for dirpath, dirnames, files in os.walk(base_directory):
    for file in files:
      with open(os.path.join(dirpath, file), 'r') as f:
        next(f)                 # skip the first line
        a_list.append(next(f))  # store the second line