在Python中将列表从文件附加到单个列表

2024-10-01 11:33:01 发布

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

我试图写一个函数,从一个包含列表的文件的“延迟”目录中读取文件。以下是延迟文件夹中的文件包含的内容:

'173378981', '45000', '343434', '3453453', '34534545', '3452342', '234234', '42063008', 'Exempted', '10000'
'1000014833', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'1000009598', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'279483421', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'1000009600', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'389453080', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'1000009602', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'

用于写入文件的函数:

^{pr2}$

我需要关于用来读取文件的函数的帮助。我只能这样写:

def getDeferredRecords():
        """docstring for getDeferredRecords"""
        infiles = [infile for infile in glob.glob(deferredDir + '/*')]
                <code to read the contents of each file here>

有人能帮我吗?我需要读一下这些行,然后把它们插入一个列表中。然后,该列表将与来自单独CSV文件的记录合并。在


Tags: 文件函数目录文件夹内容列表fordef
3条回答

the ^{} module

BigList = []
for filename in glob.glob(deferredDir + '/*'):
    PartList = csv.reader(open(filename))
    BigList.extend(PartList)

这就是你想要的吗?在

Pythoncvs模块可能是一个好的答案:
http://docs.python.org/library/csv.html

问题:

glob.glob()已经返回了一个iterable,所以我看不出这一点。。。在

[infile for infile in glob.glob(deferredDir + '/*')]

而是:

^{pr2}$

值得深思。在

首先,store函数中的最后一行必须是这样的f.close()

store函数以换行分隔的方式保存值。要阅读所有文件,应该足够:

def getDeferredRecords():
    """docstring for getDeferredRecords"""
    return dict((infile, list(iter(file(infile)))) 
                     for infile in glob.glob(deferredDir + '/*'))

说明:一个文件是iterable的,所以你可以做for line in file: print line。使用list(iter(file))可以在列表中显示文件的行。dict((a, b) for a, b in foo)返回一个包含{a: b}对的字典。函数的返回值是格式为{filename: list_of_lines_in_file}的字典。请记住,后面的字符串是新行。在

相关问题 更多 >