2

如果我有一个文件的以下目录,我将如何打开该文件然后从该文件中读取内容?如果它只是一个文件,我知道如何打开文件,当我打开文件时没有任何反应。

我有以下代码:

我想要做的是打开找到匹配的文件,然后查看该文件以查找特定行(基于其他变量),然后返回一项数据(又名,一行中的一个字段)

   data_paths = [] 
   data_paths.append(r'\\..\..\..\..\..\....\AV_only') 
   data_paths.append(r'\\..\..\...\..\..\..\all') 

 configfiles = []
for path in data_paths:
    configfiles.append(glob.glob(path+"/" + server +"*"))




heading = True
for fileListing in configfiles:
    for root, dirs, fnames in os.walk(fileListing): 
        for fname in fnames:
            print fileListing        # items is a list here
            print "Success:"


            print "Item 0" + fileListing[0]

            for elements in fileListing:
                f = file(elements,"r")
                reader = f.read()
                rownum = 0
                for row in reader:
                # Save header row.
                    if rownum == 0:
                        header = row
                    else:
                        colnum = 0
                        for col in row:
                            print '%-8s: %s' % (header[colnum], col)
                            colnum += 1

                rownum += 1

                f.close()

它没有打印任何东西,即使它应该......

我指向的文件目录将有 apx 20 个文件,例如

server1.txt
server1.csv
serverx.txt

文件类型将是 .txt 和 .csv 文件的混合:可能与此有关吗?

编辑:配置文件如下所示:

Config Files[['\\\\...\\...\\...\\...\\...\\...\\...\\x\\server.csv'], ['\\\\x\\x\\x\\x\\x\\x\\all\\server.txt']]
4

1 回答 1

0

我最近刚刚做了类似的事情。看看我能不能帮你。我想你可能想尝试这样的事情:

for elements in fileListing:
    #add this just to ensure file location
    print os.path.abspath(elements)
    for line in open(elements, 'r'):  #this does a line by line read of the file
        print line  
于 2013-06-19T15:30:08.207 回答