我正在尝试编写一个块,它将从用户处获取一个文件路径,并检查该文件路径是否a)实际上是打开文件的合法文件路径,以及b)该.txt文件的第一行和最后一行是否符合此模式:
-53.750 120.900 49.805
现在,我使用的代码不是模式匹配,而是接受任何文件。有人知道代码的哪一部分需要调整才能得到所需的过滤器吗?我觉得我错过了一些明显的东西。你知道吗
这就是我要尝试的:
while True:
try:
fileInput = input("What is the file path?: ")
openedInput = open(fileInput, 'r')
inputList = []
for line in openedInput:
inputList.append(line)
firstLine = inputList[0]
lastLine = inputList[-1]
print(firstLine)
print(lastLine)
if not re.match('.[0-9]+.[0-9]+\s.[0-9]+.[0-9]+\s[0-9]+.[0-9]+',firstLine) and re.match('.[0-9]+.[0-9]+\s.[0-9]+.[0-9]+\s[0-9]+.[0-9]+',lastLine):
print("The data file must be in XYZ format, please submit a usable file: ")
continue
break
except:
print("That file path was not valid, try again")
你有否定的问题。代码当前所做的是仅当第一行与最后一行不匹配时才打印错误消息。你知道吗
它可以与
if not (re.match(regex,firstLine) and re.match(regex,lastLine)):
或if not re.match(regex,firstLine) or not re.match(regex,lastLine):
配合使用在正则表达式中,需要在之前添加\。 像这样:[0-9]+\.[0-9]
希望有帮助,干杯。你知道吗
相关问题 更多 >
编程相关推荐