Use variables python script to open file
Question: I'm not too familiar with python, can anyone tell me how I can open files
using variables in python? I want to automate this in a script to run the same
task across multiple directories

Here machine and inputfile are variables.. I tried the following code but keep
getting errors

    
    
    file = open(machine + '/' + inputfile)
    

printing works fine.. i.e. the variables were populated correctly:

    
    
    print 'Input file is "', inputfile -> abc 
    print 'Machine "', machine -> xyz
    

Hence file location should be ./xyz/abc

Error: The error I get is file ./machine/inputfile does not exist, i.e.
instead of taking the value of the variable machine and inputfile it is taking
them as is.

Apologies if this is too trivial a question


Answer: In a general sense, there is nothing wrong with your code. There is probably
something wrong with your path and/or file name.

This is how I would do it (on windows)

    
    
    import os
    
    dir='C:/Users/xxx' # You can use forward slashes on Windows
    file='somefile.txt'
    
    full_path=os.path.join(dir,file) # OS independent way of building paths
    
    with open(full_path,'r') as f: # 'with' will automatically close file for you,
        for line in f: # Do something with the file
            print line
    

