Home > Mobile >  Writing a Python 3.9 script to parse a text file and act based on first char of line
Writing a Python 3.9 script to parse a text file and act based on first char of line

Time:10-10

I'm new to python and am struggling to figure out how to load a line from a file into a string so I can parse it and act on it. The input text file is a script for a video that will create Amazon Polly mp3 files, based on the text in the file.

The file uses the first character as either an 'A:'(action, ignore),'F:'(filename),'T:'(text for Polly),or '#' (comment, ignore) then followed by string text, For example:

#This example says that the author should move the cursor, then the corresponding Audio
#created from Polly ("Move the cursor to the specified location") is dumped into 
Move_Cursor.mp3
A:Move the cursor
T:Move the cursor to the specified location
F:Move_Cursor.mp3
#end of example

I've been trying to use the read or readline, but I can't figure out how to take the value returned by those to create a string so I can parse it.

script_file = open(input("Enter the script filename: "),'r')
lines = script_file.readlines()
cnt = 0

for line in lines:
    eol = len(line)
    print ("line length is: ",eol)
    action = line.read   #<<THIS IS WHERE I'M HAVING A TYPE ISSUE
    print ("action is  ",action)
    print ("string is  ",line)
script_file.close() 

Thank you!!!!

CodePudding user response:

line is a string from the file that was read via readlines. You could look at the first character line[0] but since you likely want the stuff after the colon also, you could split the string instead.

A few other notes. You can use with which closes the file automatically. You can enumerate the file object directly, no need for readlines. And you can count things with enumerate. Putting it all together,

with open(input("Enter the script filename: "),'r') as script_file:
    for count, line in enumerate(script_file, 1):
        action, notes = line.strip().split(":", maxsplit=1)
        print("action is", action)
        print("string is", notes)
 

CodePudding user response:

You can check the first character of every line with:

action = line[0]
  • Related