2012-08-16 36 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