首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python如何访问子文件夹的子文件夹

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

Stack Overflow用户
提问于 2012-08-17 06:31:38
回答 1查看 5.3K关注 0票数 3

我是python的新手,在访问子文件夹中的数学文本文件时遇到了问题。

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

代码语言:javascript
复制
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文件的行。

以前我有一个合并所有文件的脚本版本,但有些日志文件非常大(合并后超过16 of )。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-17 07:25:44

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

代码语言:javascript
复制
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
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11996370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档