我的目标是创建一个python脚本,该脚本将格式化/修改xml文件。 文件和文件名的路径将在命令行中作为参数提供。
以下是我的代码:
import lxml.etree as etree
from argparse import ArgumentParser
import sys
import os
def main():
parser = ArgumentParser()
parser.add_argument('-p', '--path', help="path to file's directory", required=True)
parser.add_argument('-f', '--file', help="file name", required=True)
args = parser.parse_args()
root_dir = sys.argv[1]
file_name = sys.argv[2]
path = sys.argv[1] + sys.argv[2]
for dirpath, dirnames, files in os.walk(root_dir):
for file in files:
if file == file_name:
print(os.path.join(dirpath, file_name))
with open(path, 'r', encoding="utf8") as myfile:
try:
print("DONE")
parser = etree.XMLParser(remove_blank_text = True)
tree = etree.parse(path, parser)
tree.write(path, pretty_print = True)
except IOError:
print("IO Exception Occured")
if __name__ == "__main__":
main()
当我从cmd运行它时-我有0个错误,但是即使我给出的文件名不存在,文件也没有格式化-仍然没有错误。因此,当我从cmd运行它时-没有任何反应。
当我尝试在Visual Studio中调试它时,出现错误,需要给出2个参数。 有人可以告诉我如何解决我的代码,我不知道我在哪里有错误的代码吗?
答案 0 :(得分:3)
您正在滥用/组合/混淆sys.argv
和ArgumentParser
。这段代码实际上会给您带来意想不到的结果,因为您的变量不是您想像的那样!
root_dir = sys.argv[1]
file_name = sys.argv[2]
# Add some print statements to examine these variables:
print(f'root_dir:{root_dir}')
print(f'file_name:{file_name}')
看:
执行此操作:
root_dir = args.path
file_name = args.file
这是我用来测试的代码:
from argparse import ArgumentParser
import sys
def main():
parser = ArgumentParser()
parser.add_argument('-p', '--path', help="path to file's directory", required=True)
parser.add_argument('-f', '--file', help="file name", required=True)
args = parser.parse_args()
root_dir = args.path
file_name = args.file
print(f'root_dir:{root_dir}')
print(f'file_name:{file_name}')
if __name__ == "__main__":
main()
答案 1 :(得分:1)
您正在混合两件事!
方法1
使用 rs.getDetails()
.get(0)
.getTicket()
.getHistory()
.flatMap(history->history.getServiceCouponHistory().stream())
.forEach(couponHistory -> {
if (couponHistory.getCoupon().intValue() % 4 == 1 &&
!couponHistory.getCoupon().equals(BigInteger.ONE)) {
firstConjCpnHistMap.putIfAbsent(couponHistory.getCoupon(), couponHistory);
}
});
XmlFormat.py -p c:\User\Desktop\test\ -f test.xml
方法2
使用import lxml.etree as etree
from argparse import ArgumentParser
import sys
import os
def main():
parser = ArgumentParser()
parser.add_argument('-p', '--path', help="path to file's directory", required=True)
parser.add_argument('-f', '--file', help="file name", required=True)
args = parser.parse_args()
root_dir = args.path
file_name = args.file
path = root_dir + file_name
for dirpath, dirnames, files in os.walk(root_dir):
for file in files:
if file == file_name:
print(os.path.join(dirpath, file_name))
with open(path, 'r', encoding="utf8") as myfile:
try:
print("DONE")
parser = etree.XMLParser(remove_blank_text = True)
tree = etree.parse(path, parser)
tree.write(path, pretty_print = True)
except IOError:
print("IO Exception Occured")
if __name__ == "__main__":
main()
启动(请勿使用-p和-f)
XmlFormat.py c:\User\Desktop\test\ test.xml