3

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

                    文件夹的层次结构

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

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)。

4

1 回答 1

4

这似乎对我有用。只有@jdi、@MRAB 和我指出的变化——缺少冒号和初始化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
于 2012-08-16T23:25:44.117 回答