Search code examples
sys

Taking txt files with unknown names as parameters (Python)


I am trying to write a program in Pycharm that can take the name of 2 txt files as an input and then use that input to execute some set of instructions. I understand I can put the name of a txt file in the parameters of the configuration, but how can I do that without knowing what the file name will be beforehand? The code snippet is very vague so far but I can't really do test runs without passing the 2 txt files.

import sys

sets = sys.argv[1]
operations = sys.argv[2]

print(len(sys.argv))

print(sets)
print(operations)

Even when I've tried hard-coding names of txt-files as parameters in the configuration I only get back the names of the files so I know I have more problems than one 😬.


Solution

  • "I understand I can put the name of a txt file in the parameters of the configuration, but how can I do that without knowing what the file name will be beforehand."

    In order to work with parameters unknown at the time you write your code, a filename for example in your case, you can pass those variables when you execute your python file in the terminal as arguments.

    "Even when I've tried hard-coding names of txt-files as parameters in the configuration I only get back the names of the files"

    If you want to work with the text inside the files you need to open the files first, you can't just print them like print("file1.txt")

    Code example:

    import sys
    
    file1 = sys.argv[1]
    file2 = sys.argv[2]
    
    print(f"Open and read file: {file1}")
    with open(file1, "r") as f:
        print(f.read())
    
    print(f"Open and read file: {file2}")
    with open(file2, "r") as f:
        print(f.read())
    

    Executing code (run in terminal):

    python test.py test1.txt test2.txt
    

    Output:

    Open and read file: test1.txt
    Hello World
    This is file test1
    Open and read file: test2.txt
    Hello Stackoverflow
    This is test2