使用Python修改目录和子目录中的所有PHP文件
我在扫描根目录并修改包含特定引用的所有 .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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您所怀疑的,
filename
只是文件名。文件的路径存储在root
中,所以你需要这样做As you suspected,
filename
is just the filename. The path to the file is stored inroot
, so you need to do