在给定目录的情况下在Python中打开文件

时间:2013-06-19 14:47:36

标签: python file-io

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

我有以下代码:

我想要做的是打开找到匹配的文件,然后查看该文件查找特定行(基于其他变量),然后返回一项Data(也就是一行中的一个字段)< / p>

   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']]

1 个答案:

答案 0 :(得分: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