python:读取文件并拆分数据

时间:2015-11-10 16:14:19

标签: python

我有一个文件配置,内容用空格分隔" "

cat config

/home/user1 *.log,*.txt 30
/home/user2 *.trm,*.doc,*.jpeg 10

我想读取这个文件,解析每一行并打印每行的每个字段。

例如: -

Dir = /home/user1 
Fileext = *.log,*.txt
days=30

我无法超越以下......

def dir():
        file = open('config','r+')
        cont = file.readlines()
        print "file contents are %s" % cont
        for i in range(len(cont)):
                j = cont[i].split(' ')

dir()

任何指针如何进一步移动?

2 个答案:

答案 0 :(得分:0)

你的代码很好,你只是错过了处理分割字符串的每个元素的最后一步,试试这个:

def dir():
    file = open('config','r+')
    cont = file.readlines()
    print "file contents are %s" % cont + '\n'
    elements = []
    for i in range(len(cont)):
        rowElems = cont[i].split(' ')
        elements.append({ 'dir' : rowElems[0], 'ext' : rowElems[1], 'days' : rowElems[2] })

for e in elements:
    print "Dir = " + e['dir']
    print "Fileext = " + e['ext']
    print "days = " + e['days']

dir()

在此代码的末尾,您将处理所有行并将其存储在您可以在以后轻松访问的字典数组中。

答案 1 :(得分:0)

您可以编写自定义函数来解析每一行,然后使用map函数对file.readlines()中的每一行应用该函数:

def parseLine(line):
    # function to split and parse each line,
    #  and return the formatted string
    Dir, FileExt, Days = line.split(' ')[:3]
    return 'Dir = {}\nFileext = {}\nDays = {}'.format(Dir, FileExt, Days)

def dir():
    with open('config','r+') as file:
        print 'file contents are\n' + '\n'.join(map(parseLine, file.readlines()))

结果:

>>> dir()

file contents are

Dir = /home/user1
Fileext = *.log,*.txt
Days = 30

Dir = /home/user2
Fileext = *.trm,*.doc,*.jpeg
Days = 10