微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python脚本无法识别使用中的文件

如何解决Python脚本无法识别使用中的文件

总体思路是识别输入命令文件的存在,使用存储的命令对存储了信息的文本文件进行操作,并根据选择的记录数进行输出

然而,代码始终在 if 语句之后的第一个出口处停止。我对这个有点迷茫。有什么想法吗?

import sys
import random
import shlex

#parameter check

if len(sys.argv) != 4:
    print("Usage: ./filemaker <INPUTCOMMANDFILE> <OUTPUTFILE> <RECORDCOUNT>")
    exit(1)

#store parameters in usable variables
filemaker = sys.argv[0]
inputFile = sys.argv[1]
outputfile = sys.argv[2]
recordcount = sys.argv[3]

try:
    recordcount = int(recordcount)
except:
    print("Error")
    exit(1)


try:
    inputFile =open(inputFile,'r')
except:
    print("Error with opening input file")
    exit(1)

try:
    outputFile = open(outputfile,'w')

except:
    print("Error with opening output file")
    exit(1)


#slurping commands into a commands list

cmdList = inputFile.readlines()
header = shlex.split(cmdList[0])
#declaring dictionary
randomFiles = {}

#conditional statements
if header[0] == "HEADER":
    outputFile.write(header[1].decode('string_escape'))

#slurping files into randomFiles
for i in range(len(cmdList)):
    cmd = shlex.split(cmdList[i])
    if cmd[0] == "FILEWORD":
        inFile = open(cmd[2],'r')
        randomFiles[cmd[2]] = inFile.readlines()
inFile.close()

#printing randomFiles


randomData = {}
for i in range(recordcount):
    randomData = {}
    for c in range(len(cmdList)):
        cmd = shlex.split(cmdList[c])
        if cmd[0] == "STRING":
            outputFile.write(cmd[1].decode('string_escape'))
        if cmd[0] == "FILEWORD":
            label = cmd[1]
            if label in randomData:
                print ("Error - key exists")
                exit(1)
            else:
                randWord = randomFiles[cmd[2]][random.randint(0,len(randomFiles[cmd[2]])-1)]
                randWord = randWord.rstrip()
                randomData[cmd[1]] = randWord
                outputFile.write(randomData[cmd[1]])
        if cmd[0] == "NUMBER":
            label = cmd[1]
            minNum = int(cmd[2])
            maxnum = int(cmd[3])
            if label in randomData:
                print ("Error - key exists")
                exit(1)
            else:
                randNum = random.randint(minNum,maxnum)
                randomData[cmd[1]] = str(randNum)
                outputFile.write(randomData[cmd[1]])
        if cmd[0] == "REFER":
            label = cmd[1]
            outputFile.write(randomData[label])
exit(0)

正在运行的命令行只是文件的目录所以文件夹名./filemaker(脚本的名称

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。