pythonfilecommand-promptatom-editorfile-access

Python3 file accessing


Long story short I want to do a project but don't even know where to start or how to describe it for a google search.

When I run my python file in the Command Prompt I want to be able put a text file next to it that my program will read.
Like: D:> python3 name_of_file.py name_of_text_file.txt

Now when I execute the above I want my python file to somehow see the text file to do something with it (like outputting the contents) but I don't know how to do that. Any suggestions?

Now since I don't know where to start I do not have anything to show on what I have already tried.
Incase it helps: I am using Atom. & The python file and the text file are saved in the same folder.


Solution

  • Within a python script you can use the list sys.argv. The first list element (sys.argv[0]) is the name of the python script file (in your case "name_of_file.py"). The rest of the list elements are the provided command line arguments. So sys.argv[1] will contain the first command line argument.

    import sys
    
    # Retrieve first command line argument
    file_name = sys.argv[1]
    
    # Open text file
    with open(file_name) as file:
        # Read out contents of text file
        file_text = file.read()
        
        print(file_text)