为什么python文件处理无法识别文件名?
我想用文件中的另一个字符串替换一个字符串。我有以下程序来执行任务为什么python文件处理无法识别文件名?,python,python-3.x,Python,Python 3.x,我想用文件中的另一个字符串替换一个字符串。我有以下程序来执行任务 import os import sys import traceback from glob import iglob def usage(): print('Usage: python FindAndReplace.py [Old String] [New String] ' '[File Filters(default:".txt,.xml")] [Directory To
import os
import sys
import traceback
from glob import iglob
def usage():
print('Usage: python FindAndReplace.py [Old String] [New String] '
'[File Filters(default:".txt,.xml")] [Directory To Check(.)]')
def search_replace_string(fileName, old_str, new_str):
if not(os.path.isfile(fileName) and os.access(fileName, os.W_OK)):
print("Warning: Skipping..File does not exist or and is not writeable:" + filename)
return False
fileupdated = False
# Read the old file
with open(fileName, 'r') as f:
newlines = []
for lines in f.readlines():
if old_str in lines:
fileupdated = True
line = lines.replace(old_str, new_str)
newlines.append(line)
# Write changes to same file
if fileupdated:
print("string Found and Updating File: " + fileName)
try:
with open(fileName, 'w') as f:
for line in newlines:
f.write(line)
except:
print("Error: Cannot open/access existing file for writing: " + fileName)
return fileupdated
def main():
try:
DEFAULT_PATH = iglob(str('<path_to_file.xml'))
if len(sys.argv) < 3:
usage()
# old/new string required parameters, exit if not supplied
sys.exit(-1)
else:
oldString = sys.argv[1]
newString = sys.argv[2]
if len(sys.argv) < 4:
patterns = ['.xml', '.txt']
else:
stringFilter = sys.argv[3]
patterns = stringFilter.split(',')
if len(sys.argv) < 5:
path = DEFAULT_PATH
else:
path = sys.argv[4]
print('[Old String] :' + oldString)
print('[New String] :' + newString)
print('[File Filters] :' + ', '.join(patterns))
print('[Directory To Check] :' + path)
if not os.path.exists(path):
raise Exception("Selected path does not exist: " + path)
# Walk through directory structure looking for files matching patterns
matchingFileList = [os.path.join(dp, f) for dp, dn, filenames in os.walk(path) for f in filenames if os.path.splitext(f)[1] in patterns]
print('Files found matching patterns: ' + str(len(matchingFileList)))
filecount = 0
filesReplaced = 0
for currFile in matchingFileList:
filecount += 1
filesReplaced = search_replace_string(currFile, old_str, new_str)
if filesReplaced:
filesReplaced += 1
print("Total Files Searched :" + str(filecount))
print("Total Files Replaced/Updated :" + str(filesReplaced))
except Exception as err:
print(traceback.format_exception_only(type(err), err)[0].rstrip())
sys.exit(-1)
if __name__ == '__main__':
main()
下面是我给出的命令行参数
python uro.py <file_path> <old_str> <new_str>
python uro.py
注意:我使用的是xml文件。
我想开发一种逻辑,将文件名、新旧字符串作为命令行参数。在错误中,可以看到程序将python文件视为输入文件。而它应该采用我用CMD参数给出的文件路径
这里怎么了?请建议。谢谢我修好了,有一些路径问题。谢谢。什么是
uro.py
与问题的其余部分有什么关系?urp.py包含搜索匹配的sting并替换为新sting的代码。哦,你的意思是uro.py
包含你发布的代码?那么,它在哪里?代码是你自己在某种编辑器中编写的吗?你把文件保存在哪里了?我已经用pycharm写了代码。但通过CMD行执行它,参数如我的原始帖子所示。那么PyCharm在哪里存储了这个文件?在运行命令行之前,您是否已将cd
放入此文件夹?
python uro.py <file_path> <old_str> <new_str>