python初学者如何将几个文件的内容读入唯一列表?

2024-09-27 07:31:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将几个文件中的内容读入唯一的列表,以便以后调用-最终,我想将这些列表转换为集合,并对它们执行交集和减法。这一定是一个非常天真的问题,但是在仔细研究了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)?

非常感谢你为一个完整的编程初学者指出了正确的方向!


Tags: 文件in列表forlensysrangeopen
3条回答
#!/usr/bin/env python

import sys

FileList = sys.argv[1: ]
PathwayList = []
for InFileName in FileList:
    sys.stderr.write("Processing file %s\n" % (i))
    InFile = open(InFileName, 'r')
    PathwayList.append(InFile.readlines())
    InFile.close()

假设您读了两个文件,下面将逐行比较(它不会在较长的文件中提取任何额外的行,但是如果一个文件的行数多于另一个文件的行数,那么它们就不一样了;)

for i, s in enumerate(zip(PathwayList[0], PathwayList[1]), 1):
    if s[0] == s[1]:
        print i, 'match', s[0]
    else:
        print i, 'non-match', s[0], '!=', s[1]

对于您想要做的事情,您可能需要查看Python中的difflib模块。要进行排序,请查看Mutable Sequence TypessomeListVar.sort()将对someListVar的内容进行排序。

您可能想查看Python的fileinput模块,它是标准库的一部分,允许您同时处理多个文件。

如果不需要记住内容的来源,可以这样做:

PathwayList = []
for InFileName in FileList:
    sys.stderr.write("Processing file %s\n" % InFileName)
    InFile = open(InFileName, 'r')
    PathwayList.append(InFile.readlines())
    InFile.close()  

for contents in PathwayList:
    # do something with contents which is a list of strings
    print contents  

或者,如果要跟踪文件名,可以使用字典:

PathwayList = {}
for InFileName in FileList:
    sys.stderr.write("Processing file %s\n" % InFileName)
    InFile = open(InFileName, 'r')
    PathwayList[InFile] = InFile.readlines()
    InFile.close()

for filename, contents in PathwayList.items():
    # do something with contents which is a list of strings
    print filename, contents  

相关问题 更多 >

    热门问题