How to open multiple file paths?

430 Views Asked by At

I now have a file with a list of file paths. I want to loop open them to read and write. Can anyone suggest how to do this? Everything I have seen so far is only to read these lines and print them out, I want my code to open these paths. Below is a slice of the path file:

E:\Grad\LIS\LIS590 Text mining\Part1\Part1\awards_1994\awd_1994_96\a9496340.txt
E:\Grad\LIS\LIS590 Text mining\Part1\Part1\awards_1994\awd_1994_96\a9496341.txt
E:\Grad\LIS\LIS590 Text mining\Part1\Part1\awards_1994\awd_1994_96\a9496342.txt
E:\Grad\LIS\LIS590 Text mining\Part1\Part1\awards_1994\awd_1994_96\a9496343.txt
E:\Grad\LIS\LIS590 Text mining\Part1\Part1\awards_1994\awd_1994_96\a9496344.txt
E:\Grad\LIS\LIS590 Text mining\Part1\Part1\awards_1994\awd_1994_96\a9496345.txt
E:\Grad\LIS\LIS590 Text mining\Part1\Part1\awards_1994\awd_1994_96\a9496346.txt
E:\Grad\LIS\LIS590 Text mining\Part1\Part1\awards_1994\awd_1994_96\a9496347.txt
E:\Grad\LIS\LIS590 Text mining\Part1\Part1\awards_1994\awd_1994_96\a9496348.txt
E:\Grad\LIS\LIS590 Text mining\Part1\Part1\awards_1994\awd_1994_96\a9496349.txt
E:\Grad\LIS\LIS590 Text mining\Part1\Part1\awards_1994\awd_1994_96\a9496350.txt
E:\Grad\LIS\LIS590 Text mining\Part1\Part1\awards_1994\awd_1994_96\a9496351.txt
...

This is the code I am trying:

def work_on(r'E:\Grad\LIS\LIS590 Text mining\file+test.txt'):  # The last quotation mark gives me that error. I also tried double quotation mark, didn't work either.
    with open(r'E:\Grad\LIS\LIS590 Text mining\file+test.txt', 'r') as data_file:

with open('file_list.txt', 'r') as file_list:    #file_list.txt is the file name I saved all the paths.
    for filename in file_list:
        with open(filename, 'r') as data_file:
            work_on(filename)
1

There are 1 best solutions below

7
On

The general flow will be the same as printing out the lines - the only difference is instead of using print() you will do other work (in this case opening a file and working with it):

with open('/your/file/list.txt', 'r') as file_list:
    for filename in file_list:
        with open(filename, 'r') as data_file:
            # work with data_file here

You can then factor out the second piece of work into a separate function if that makes sense:

def work_on(data_file_path):
    with open(data_file_path, 'r') as data_file:
        # work with data_file here

which would then simplify your work loop to:

with open('/your/file/list.txt', 'r') as file_list:
    for filename in file_list:
        work_on(filename)