使用Python修改目录和子目录中的所有PHP文件

发布于 2025-01-16 09:49:52 字数 764 浏览 3 评论 0原文

我在扫描根目录并修改包含特定引用的所有 .php 文件时遇到问题。本质上,我们希望迁移整个数据库。我必须找到某些表的所有记录并适当地重命名它们。这是我到目前为止的代码:

import os
import re

directory = 'C:/Users/me/Desktop/wsphp'

for root, dirs, files in os.walk(directory):
    for filename in files:
        if filename.endswith('.php'):
            print(filename)
            open_file = open(filename, 'r')
            read_file = open_file.read()
            regex = re.compile('OLD DATABASE NAME')
            read_file = regex.sub('NEW DATABASE NAME', read_file)
            write_file = open(filename, 'w')
            write_file.write(read_file)

我的代码在尝试打开文件时中断。问题似乎是“文件名”仅指没有整个目录的文件名(“index.php”而不是“C:/Users/me/Desktop/wsphp/Subfolder/Subfolder2/index.php”)。根目录包含一些 .php 文件以及一堆子目录。有没有更简单的方法来解决这个问题?

I'm having issues scanning through a root directory and modifying all .php files that contain a certain reference. Essentially, we're looking to move our entire database. I have to find all records of certain tables and rename them appropriately. Here's the code I have so far:

import os
import re

directory = 'C:/Users/me/Desktop/wsphp'

for root, dirs, files in os.walk(directory):
    for filename in files:
        if filename.endswith('.php'):
            print(filename)
            open_file = open(filename, 'r')
            read_file = open_file.read()
            regex = re.compile('OLD DATABASE NAME')
            read_file = regex.sub('NEW DATABASE NAME', read_file)
            write_file = open(filename, 'w')
            write_file.write(read_file)

My code breaks when it attempts to open the file. The problem seems to be that 'filename' refers to JUST the filename without the entire directory ('index.php' rather than 'C:/Users/me/Desktop/wsphp/Subfolder/Subfolder2/index.php'). The root directory contains a few .php files as well as a bunch of subdirectories. Is there an easier way to go about this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼眸 2025-01-23 09:49:52

正如您所怀疑的,filename 只是文件名。文件的路径存储在root中,所以你需要这样做

open_file = open(os.path.join(root, filename), 'r')

As you suspected, filename is just the filename. The path to the file is stored in root, so you need to do

open_file = open(os.path.join(root, filename), 'r')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文