简体   繁体   中英

How to read a text file line by line like a set of commands

I have a text file that has written a function name along with the parameters such as "insert 3" where I need to read the insert and 3 individually to call a function insert with parameter 3.

I have so far opened the file and called .readlines() on it to separate each line into a list of each line of text. I am now struggling to find a way to apply .split() to each element recursively. I am to do this with functional programming and I cannot use a for loop to apply the .split() function.

def execute(fileName):
    file = open(fileName + '.txt', 'r').readlines()
    print(file)
    reduce(lambda x, a: map(x, a), )

I would like to use each line independently with different amounts of parameters so I can call my test script and have it run each function.

Hey I just wrote the code on repl.it you should check it out. But here is the breakdown.

  1. Read each line from file
  2. Now you should a list where each element is a new line from the file

     lines = ["command argument", "command argument" ... "command argument"] 
  3. Now iterate through each element in the list where you split the element at the " " (space character) and append it to a new list where all the commands and their respective arguments will be stored.

     for line in lines: commands.append(line.split(" ")) 
  4. Now the commands list should be a multidimensional array containing data like

     commands = [["command", "argument"], ["command", "argument"], ... ["command", "argument"]] 
  5. Now you can just iterate through each sub-list where value at index 0 is the command and value at index 1 is the argument. After this you can use if statements to check for what command/ function to run with what datatype as an argument

HERE IS THE WHOLE CODE:

    command = []
    with open("command_files.txt", "r") as f:
        lines = f.read().strip().split("\n") # removing spaces on both ends, and spliting at the new line character \n
        print(lines) # now we have a list where each element is a line from the file
        # breaking each line at " " (space) to get command and the argument
        for line in lines:
            # appending the list to command list
            command.append(line.split(" "))
       # now the command list should be a multidimensional array
       # we just have to go through each of the sub list and where the value at 0 index should be the command, and at index 1 the arguments
       for i in command:
           if i[0] == "print":
               print(i[1])
           else:
               print("Command not recognized")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM