Python 2.5.2:尝试递归打开文件
下面的脚本应该能递归地打开文件夹'pruebaba'里的所有文件,但我遇到了这个错误:
追踪记录(最近的调用在最前面):
文件 "/home/tirengarfio/Desktop/prueba.py", 第8行,在 f = open(file,'r') IOError: [错误号 21] 是一个目录
这是文件的层级结构:
pruebaba
folder1
folder11
test1.php
folder12
test1.php
test2.php
folder2
test1.php
脚本内容:
import re,fileinput,os
path="/home/tirengarfio/Desktop/pruebaba"
os.chdir(path)
for file in os.listdir("."):
f = open(file,'r')
data = f.read()
data = re.sub(r'(\s*function\s+.*\s*{\s*)',
r'\1echo "The function starts here."',
data)
f.close()
f = open(file, 'w')
f.write(data)
f.close()
有什么想法吗?
3 个回答
1
os.listdir 会列出文件和文件夹。你应该检查一下你想打开的东西到底是不是一个文件,可以用 os.path.isfile 来确认。
14
使用 os.walk
。这个功能会自动进入一个文件夹及其所有子文件夹,帮你找到里面的文件和文件夹,并且会把它们分开给你。
import re
import os
from __future__ import with_statement
PATH = "/home/tirengarfio/Desktop/pruebaba"
for path, dirs, files in os.walk(PATH):
for filename in files:
fullpath = os.path.join(path, filename)
with open(fullpath, 'r') as f:
data = re.sub(r'(\s*function\s+.*\s*{\s*)',
r'\1echo "The function starts here."',
f.read())
with open(fullpath, 'w') as f:
f.write(data)