【发布时间】:2018-11-22 15:36:38
【问题描述】:
我正在创建一个简单的 python 脚本来查找和替换文件中的字符串,这些文件也位于子文件夹等中。这需要递归。
以下脚本查找并替换在目标父文件夹的每个文件夹内的每个文件中找到的另一个字符串。
我在这里发现这篇文章建议使用 fileinput 模块以避免将整个文件读入内存,这可能会减慢速度...
...simplify the text replacement in a file without requiring to read the whole file in memory...
Python 非常动态,老实说,我迷失在完成同一任务的许多不同方法上。
如何将这种方法集成到下面的脚本中?
import subprocess, os, fnmatch
if os.name == 'nt':
def clear_console():
subprocess.call("cls", shell=True)
return
else:
def clear_console():
subprocess.call("clear", shell=True)
return
# Globals
menuChoice = 0
searchCounter = 0
# Recursive find/replace with file extension argument.
def findReplace(directory, find, replace, fileExtension):
global searchCounter
#For all paths, sub-directories & files in (directory)...
for path, dirs, files in os.walk(os.path.abspath(directory)):
#For each file found with (FileExtension)...
for filename in fnmatch.filter(files, fileExtension):
#Construct the target file path...
filepath = os.path.join(path, filename)
#Open file correspondent to target filepath.
with open(filepath) as f:
# Read it into memory.
s = f.read()
# Find and replace all occurrances of (find).
s = s.replace(find, replace)
# Write these new changes to the target file path.
with open(filepath, "w") as f:
f.write(s)
# increment search counter by one.
searchCounter += 1
# Report final status.
print (' Files Searched: ' + str(searchCounter))
print ('')
print (' Search Status : Complete')
print ('')
input (' Press any key to exit...')
def mainMenu():
global menuChoice
global searchCounter
# range lowest index is 1 so range of 6 is 1 through 7.
while int(menuChoice) not in range(1,1):
clear_console()
print ('')
print (' frx v1.0 - Menu')
print ('')
print (' A. Select target file type extension.')
print (' B. Enter target directory name. eg -> target_directory/target_subfolder')
print (' C. Enter string to Find.')
print (' D. Enter string to Replace.')
print ('')
print (' Menu')
print ('')
menuChoice = input('''
1. All TXT files. (*.txt )
Enter Option: ''')
print ('')
# Format as int
menuChoice = int(menuChoice)
if menuChoice == 1:
fextension = '*.txt'
# Set directory name
tdirectory = input(' Target directory name? ')
tdirectory = str(tdirectory)
print ('')
# Set string to Find
fstring = input(' String to find? (Ctrl + V) ')
fstring = str(fstring)
print ('')
# Set string to Replace With
rstring = input(' Replace with string? (Ctrl + V) ')
rstring = str(rstring)
print ('')
# Report initial status
print (' Searching for occurrences of ' + fstring)
print (' Please wait...')
print ('')
# Call findReplace function
findReplace('./' + tdirectory, fstring, rstring, fextension)
# Initialize program
mainMenu()
# Action Sample...
#findReplace("in this dir", "find string 1", "replace with string 2", "of this file extension")
# Confirm.
#print("done.")
【问题讨论】:
-
我猜是
for line in FileInput(files, inplace=True):line.replace(text, replacement)部分,files使用fnmatch.filter(files, fileExtension)
标签: python python-3.x file recursion directory