我是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文件的行。
以前我有一个合并所有文件的脚本版本,但有些日志文件非常大(合并后超过16 of )。
发布于 2012-08-17 07:25:44
这似乎对我很有效。只有@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 += 1https://stackoverflow.com/questions/11996370
复制相似问题