2012-08-16 52 views
3

我是新来的Python和我有麻烦访问的子文件夹中的数学文本文件的子文件夹。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

你得到一个错误? (除了在打开文件的行后面以及在'special_file'测试行后面缺少':' – jdi 2012-08-16 22:33:17

+0

)您收到了什么错误?或者输出是什么?那里有一些语法错误,但我假设这只是由于复制粘贴的东西,是吗? – RocketDonkey 2012-08-16 22:34:37

+1

另外'counter'尚未被初始化为0 – MRAB 2012-08-16 22:47:25

回答

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 
+3

只是用斜杠对于路径,甚至在窗口上。 – jdi 2012-08-16 23:35:29

+0

@jdi哈,我一直在想'必须有更好的办法'。谢谢你的提示!现在解决。 – RocketDonkey 2012-08-16 23:37:45

+0

哈哈,它很高兴知道它的普遍处理。 +1现在你已经修复了! – jdi 2012-08-16 23:41:35