我现在有一个包含文件路径列表的文件。我想循环打开它们进行读写。任何人都可以建议如何做到这一点?到目前为止我所看到的一切只是阅读这些行并打印出来,我希望我的代码打开这些路径。下面是路径文件的一部分:
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
...
这是我正在尝试的代码:
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)
答案 0 :(得分:3)
一般流程与打印行相同 - 唯一的区别是使用print()
而不是使用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
您将完成其他工作(在这种情况下打开文件并使用它):
def work_on(data_file_path):
with open(data_file_path, 'r') as data_file:
# work with data_file here
如果有意义的话,你可以把第二部分工作分解成一个单独的函数:
with open('/your/file/list.txt', 'r') as file_list:
for filename in file_list:
work_on(filename)
然后将工作循环简化为:
{{1}}