gpt4 book ai didi

python 2.5.2 : trying to open files recursively

转载 作者:太空狗 更新时间:2023-10-29 22:08:33 26 4
gpt4 key购买 nike

下面的脚本应该递归地打开“pruebaba”文件夹中的所有文件,但我收到此错误:

Traceback (most recent call last):
File "/home/tirengarfio/Desktop/prueba.py", line 8, in f = open(file,'r') IOError: [Errno 21] Is a directory

这是层次结构:

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()

有什么想法吗?

最佳答案

使用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)

关于 python 2.5.2 : trying to open files recursively,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2578022/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com