Accessing a file path saved in a .txt file. (Python)
Question: I have a text file that contains file paths of files that I wish to open.

The text file looks like this:

    
    
    28.2 -1.0 46 14 10 .\temp_109.17621\voltage_28.200\power_-1.txt
    28.2 -2.0 46 16 10 .\temp_109.17621\voltage_28.200\power_-2.txt
    

...

I would like to open the files at this filepath.

First step is to load each filepath from the text file.

I've tried this using:

    
    
    path = np.loadtxt('NonLorentzianData.txt',usecols=[5],dtype='S16')
    

which generates a `path[1]` that looks like:

`.\\temp_109.17621` ...

rather than the entire file path.

Am I using the wrong `dtype` or is this not possible with `loadtxt`?


Answer: If you change the data type to `np.str_` it will work:

    
    
    path = np.loadtxt('NonLorentzianData.txt',usecols=[5],dtype=np.str_)
    
    print(path[1])
    .\temp_109.17621\voltage_28.200\power_-2.txt
    

Or using `dtype=("S44")` will also work which is the length of your longest of
the two paths. You are specifying a _16 character string_ so you only get the
_first 16 characters_.

    
    
    In [17]: s = ".\\temp_109.17621"
    
    In [18]: len(s)
    Out[18]: 16
    
    # 43 character string
    In [26]: path = np.loadtxt('words.txt',usecols=[5],dtype=("S43"))    
    In [27]: path[1]
    Out[27]: '.\\temp_109.17621\\voltage_28.200\\power_-2.tx'    
    In [28]: len(path[1])
    Out[28]: 43    
    # 38 character string
    In [29]: path = np.loadtxt('words.txt',usecols=[5],dtype=("S38"))    
    In [30]: path[1]
    Out[30]: '.\\temp_109.17621\\voltage_28.200\\power_'    
    In [31]: len(path[1])
    Out[31]: 38
    In [32]: path = np.loadtxt('words.txt',usecols=[5],dtype=np.str_)
    In [33]: path[1]
    Out[33]: '.\\temp_109.17621\\voltage_28.200\\power_-2.txt'
    

If you look at the
[docs](http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html) you will
see what every dtype does and how to use them.

If you just want all the file paths you can also use `csv.reader`:

    
    
    import csv
    with open("NonLorentzianData.txt") as f:
        reader = csv.reader(f,delimiter=" ")
        for row in reader:
            with open(row[-1]) as f:
                .....
    

