【问题标题】:python opening files from multiple directories(folders)python从多个目录(文件夹)打开文件
【发布时间】:2013-10-24 01:15:52
【问题描述】:

我在多个目录中有多个文件,并希望迭代每个目录以运行我的代码。我写过这样的代码。

import os

path = [".\\folder1\\",".\\forder2\\"]
for i in path:
    # print (i) # test
    for filename in os.listdir(i):
        filedata = open(i+filename,"r")
        data = filedata.read().split()
        string = "".join(data)
        filedata.close()

但是,由于 i 不具体,它会出错。 每个文件夹都包含字符串,通过os.listdir访问。

从多个目录读取文件时如何解决这个问题?

提前谢谢你。

【问题讨论】:

  • 您是要更改文件数量,还是只有两个?
  • 实际上,我要更改要添加到“路径”列表中的目录数量。我想 os.listdir 读取目录中的所有文件。谢谢。

标签: python operating-system


【解决方案1】:

尝试使用os.path.join

path = ["folder1", "folder2"]
for i in path:
    for filename in os.listdir(i):
        with open(os.path.join(i, filename), 'r') as filedata:
            string = "".join(filedata.read().split())

【讨论】:

  • 感谢您的帮助,但它得到 'TypeError: object of type 'int' has no len()' 和 '~~in join assert len(path) >0' I don' t 收到消息,错误不具体...希望有任何其他建议。
  • 哦,我的错。我在我的代码中使用了相同的变量“i”两次!这完美!谢谢乔莎!
  • 很高兴它有帮助,@Karyo :)
猜你喜欢
  • 1970-01-01
  • 2015-08-21
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
相关资源
最近更新 更多