Reading files from command line


import sys

NUM_LINES = 10

# Verify that exactly one command line argument (in addition to the .py file) was supplied

if len(sys.argv) != 2:

    print("Provide the file name as a command line argument.")

    quit() 

# Open the file for reading

    inf = open(sys.argv[1], "r")

# Read the first line from the file

    line = inf.readline()

# Keep looping until we have either read and displayed 10 lines or we have reached the end

# of the file

    count = 0

    while count < NUM_LINES and line != "":

# Remove the trailing newline character and count the line

        line = line.rstrip()

        count = count + 1

# Display the line

        print(line)

# Read the next line from the file

        line = inf.readline()

# Close the file

inf.close()

This is the code and the error says to provide the file name as a command line argument but the comment says, it needs,a py file too, can you have a py file and a txt file at the same time, l am confused? Please help

Verify that exactly one command line argument (in addition to the .py file) was supplied

Thanks

The exercise is this:

Unix-based operating systems usually include a tool named head. It displays the
first 10 lines of a file whose name is provided as a command line argument. Write
a Python program that provides the same behaviour. Display an appropriate error
message if the file requested by the user does not exist, or if the command line
argument is omitted.

Yes. What have you tried entering as a command?

I tried entering the location of a txt in the command prompt, which was on my desktop, so it opened in the command prompt but nothing happened in the VS Code

I tried entering a py file in the command prompt, it asks to choose an IDE to open it

I also checked a youtube video, and tried to see what the person was doing, and tried but didn’t manage

What you will probably need to do is enter the command to run a python file, so:

python somefile.py
#or
python3 somefile.py
#or
py somefile.py
# however you normally run a .py file

Now, if your python file takes an argument, you simply provide it in the same line following a space:

python somefile.py sometextfile.txt

That should do it.

ok l have tried to do that but the code is showing blank


Not sure what the second screenshot has to do with anything, but in your first screenshot, I see a few problems.

First, The file that takes a .txt file as a parameter is test.py, but in your command prompt you typed script.py text.txt.

Second, what you typed in the command prompt is missing a key element. You have to specify that you want python to run the program. It would be more simple to navigate to the folder that contains both your test.py and text.txt file first, and then enter the command, otherwise you’ll have to supply the path to each file in the command.

Third, your code in the test.py file won’t even open the text.txt file let alone print lines from it. The code that does those things is unreachable. Can you see why? Think about what indentation does in python.

I am getting this error, the original code had a try and except statement, but l saw the except statement was having an issue so l removed it but it is not showing an error now


import sys

NUM_LINES = 10

# Verify that exactly one command line argument (in addition to the .py file) was supplied

if len(sys.argv) != 2:

    print("Provide the file name as a command line argument.")

    quit() 

try:

# Open the file for reading

    inf = open(sys.argv[1], "r")

# Read the first line from the file

    line = inf.readline()

# Keep looping until we have either read and displayed 10 lines or we have reached the end

# of the file

    count = 0

    while count < NUM_LINES and line != "":

# Remove the trailing newline character and count the line

        line = line.rstrip()

        count = count + 1

# Display the line

        print(line)

# Read the next line from the file

        line = inf.readline()

# Close the file

    inf.close()

except IOError:

# Display a message if something goes wrong while accessing the file

    print("An error occurred while accessing the file.")

In your screenshot, the command prompt shows line 25 as inf.close(), but in the code, that is line 27. Have you tried running the code shown in the screenshot since saving it?

EDIT:
Never mind the above. It’s likely due to the 2 blank lines at the beginning of test.py.
I just noticed that you are still running the program from the location C:WINDOWS\System32 rather than navigating to your .vscode folder first. Since you are doing it that way, you have to provide the full path to the text.txt file as well. Since you haven’t, inf gets assigned to undefined here in test.py:

inf = open(sys.argv[1], "r") # if you print sys.argv[1] you should see: text.txt
# text.txt is not in the location you are executing the command from

By this you mean l open the command prompt there or I don’t get it, the difference in the line number I don’t know why, l tried again

You either need to use the cd command to change the directory you’re in before executing your command, or provide the full path to both files in the command. You provide the full path to test.py, but you only put the filename for text.txt.
Either do this first: (navigate to the folder where the files are located)

cd C:/Users/simmy/.vscode

then:

C:\Users\simmy\.vscode>test.py text.txt

OR, change your command to: (provide full path to both files)

C:\WINDOWS\system32>C:\Users\simmy\.vscode\test.py C:\Users\simmy\text.txt
1 Like

I still get the same error

Could you post your full code in test.py, please? Preferably not a screenshot.


import sys

NUM_LINES = 10

# Verify that exactly one command line argument (in addition to the .py file) was supplied

if len(sys.argv) != 2:

    print("Provide the file name as a command line argument.")

    quit() 

try:

# Open the file for reading

    inf = open(sys.argv[1], "r")

# Read the first line from the file

    line = inf.readline()

# Keep looping until we have either read and displayed 10 lines or we have reached the end

# of the file

    count = 0

    while count < NUM_LINES and line != "":

# Remove the trailing newline character and count the line

        line = line.rstrip()

        count = count + 1

# Display the line

        print(line)

# Read the next line from the file

        line = inf.readline()

# Close the file

    inf.close()

except IOError:

# Display a message if something goes wrong while accessing the file

    print("An error occurred while accessing the file.")

This is the test.py full code

Ok. I ran your code on my machine with no issues. Unless you have another instance of test.py somewhere on your computer, and aren’t running the one you’re editing, I don’t know what the problem could be. From the location shown in your screenshot, which is: C:\Users\simmy\.vscode>, enter the following command:

C:\Users\simmy\.vscode>type test.py

This will print the contents of the file to your console. See if the code matches what you posted above. If you post a screenshot of it, I’ll also take a look.

It has ran now

Thanks

1 Like

I don’t know why l am having problems with command line, in this code l am getting an error also

Thanks

Look at your first if statement. You changed it. That condition will never evaluate to truthy.

Edit: I misspoke, That condition will always be truthy. sys.argv is a list of the arguments passed from the command line. That list will never, ever be equal to 2 when test.py is run. It’s impossible.

I have added two items test.py and text.txt so its equal to 2, so the if statement should be false

I edited my previous post, but consider what your if condition is testing. In your screenshot, if we substitute the actual values into your if condition:

if ['test.py', 'text.txt'] != 2:
    #print message
    quit()

Since the list will never be equal to 2, the message will always print, and you will quit the program.

No. sys.argv is assigned to a list with a length of 2, but sys.argv is not assigned to the integer, 2.

sorry for that, forgot to add len(), now its showing that it cannot find file