Python如何访问子文件夹的子文件夹

时间:2012-08-16 22:31:38

标签: python python-2.7

我是python的新手,我无法访问子文件夹中的数学文本文件。

Hierarchy of the folder

这是我到目前为止编写的代码:

import os, sys
for folder, sub_folders, files in os.walk(my_directory):
   for special_file in files:
      if special_file == 'math.txt'
         file_path = os.path.join(folder, special_file)
         with open(file_path, 'r+') as read_file
            counter += 1
            print('Reading math txt file' + str(counter))

            for line in read_file:
               print(line)

我无法对所有班级以及所有学校和所有区域中的所有math.txt文件进行打印。

在我有一个合并所有文件的脚本版本之前,但有些日志文件非常大(组合> 16GB)。

1 个答案:

答案 0 :(得分:4)

这似乎对我有用。只有@jdi,@ RMAB和我指示的变化 - 缺少冒号并初始化counter变量。由于您使用的是Windows,因此您可能需要确保正确指定目录路径。

import os, sys

# Specify directory
# In your case, you may want something like the following
my_directory = 'C:/Users/<user_name>/Documents/ZoneA'

# Define the counter
counter = 1

# Start the loop
for folder, sub_folders, files in os.walk(my_directory):
  for special_file in files:
    if special_file == 'math.txt':
      file_path = os.path.join(folder, special_file)

      # Open and read
      with open(file_path, 'r+') as read_file:
        print('Reading math txt file ' + str(counter))

        # Print the file
        for line in read_file:
           print(line)

        # Increment the counter
        counter += 1