Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6687143
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T05:15:14+00:00 2026-05-26T05:15:14+00:00

I have a random line generator program written in Python2, but I need to

  • 0

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/python

import random, sys
from optparse import OptionParser

class 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 66
    except IOError as (errno, strerror):
                      ^
SyntaxError: invalid syntax

Can you tell me what this error means and how to fix it?

Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T05:15:14+00:00Added an answer on May 26, 2026 at 5:15 am

    This line is incorrect syntax:

    except IOError as (errno, strerror):
    

    The correct form is:

    except IOError as err:
    

    then you can examine err for attributes like errno, etc.

    I’m not sure where you got the original line from, it isn’t valid Python 2.x syntax either.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a program that uses the mt19937 random number generator from boost::random. I
I have a txt file and each line has a set of random strings,
I have a pseudo random number generator (PRNG) class that I want to unit
Possible Duplicate: True random number generator I have worked with random functions in python,ruby,
I have a simple wrapper for an Mersenne twister random number generator. The purpose
i have problem with substitution. I have a file with 1 line of random
Possible Duplicate: Why does this Random Number Generator not random? I have this test
I have some problem with sequence generator. I have a file where each line
I have a standalone Java application below that is: Generating a random line Applied
I have the following C++ code that tried to generate a random number. The

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.