我想将几个文件中的内容读入唯一的列表,以便以后调用-最终,我想将这些列表转换为集合,并对它们执行交集和减法。这一定是一个非常天真的问题,但是在仔细研究了Lutz的“学习Python”中的迭代器和循环部分之后,我似乎无法理解如何处理这个问题。以下是我写的:
#!/usr/bin/env python
import sys
OutFileName = 'test.txt'
OutFile = open(OutFileName, 'w')
FileList = sys.argv[1: ]
Len = len(FileList)
print Len
for i in range(Len):
sys.stderr.write("Processing file %s\n" % (i))
FileNum = i
for InFileName in FileList:
InFile = open(InFileName, 'r')
PathwayList = InFile.readlines()
print PathwayList
InFile.close()
通过几个简单的测试文件,我得到如下输出:
Processing file 0
Processing file 1
['alg1\n', 'alg2\n', 'alg3\n', 'alg4\n', 'alg5\n', 'alg6']
['csr1\n', 'csr2\n', 'csr3\n', 'csr4\n', 'csr5\n', 'csr6\n', 'csr7\n', 'alg2\n', 'alg6']
这些列表是正确的,但是我如何将每个列表分配给一个唯一的变量,以便以后可以调用它们(例如,通过在变量名中包含index#from range)?
非常感谢你为一个完整的编程初学者指出了正确的方向!
假设您读了两个文件,下面将逐行比较(它不会在较长的文件中提取任何额外的行,但是如果一个文件的行数多于另一个文件的行数,那么它们就不一样了;)
对于您想要做的事情,您可能需要查看Python中的difflib模块。要进行排序,请查看Mutable Sequence Types,
someListVar.sort()
将对someListVar的内容进行排序。您可能想查看Python的fileinput模块,它是标准库的一部分,允许您同时处理多个文件。
如果不需要记住内容的来源,可以这样做:
或者,如果要跟踪文件名,可以使用字典:
相关问题 更多 >
编程相关推荐