I have a random line generator program written in Python2, but I need to port it to Python3. You give the program the option -n [number] and a file argument to tell it to randomly output [number] number of lines from the file. Here is the source for the program:
#!/usr/bin/pythonimport random, sys
from optparse import OptionParserclass randline:def __init__(self, filename):f = open(filename, 'r')self.lines = f.readlines()f.close()def chooseline(self):return random.choice(self.lines)def main():version_msg = "%prog 2.0"usage_msg = """%prog [OPTION]... [FILE] [FILE]...Output randomly selected lines from each FILE."""parser = OptionParser(version=version_msg,usage=usage_msg)parser.add_option("-n", "--numlines",action="store", dest="numlines", default=1,help="output NUMLINES lines (default 1)")options, args = parser.parse_args(sys.argv[1:])try:numlines = int(options.numlines)except:parser.error("invalid NUMLINES: {0}".format(options.numlines))if numlines < 0:parser.error("negative count: {0}".format(numlines))if len(args) < 1:parser.error("input at least one operand!")for index in range(len(args)):input_file = args[index]try:generator = randline(input_file)for index in range(numlines):sys.stdout.write(generator.chooseline())except IOError as (errno, strerror):parser.error("I/O error({0}): {1}".format(errno, strerror))if __name__ == "__main__":main()
When I run this with python3:
python3 randline.py -n 1 file.txt
I get the following error:
File "randline.py", line 66except IOError as (errno, strerror):^
SyntaxError: invalid syntax
Can you tell me what this error means and how to fix it?
Thanks!