【问题标题】:Can`t use the files inside my subdirectories无法使用我的子目录中的文件
【发布时间】:2019-06-20 02:36:45
【问题描述】:

我正在创建一个可以从某些 txt 文件中读取某些数据的程序,当我尝试使用子目录中的文件时出现问题(子目录位于程序的主目录中。我使用的是选择查找所有文件,然后使用我找到的信息创建一个新文件。主要问题是我无法读取这些文件。

我尝试使用用于创建目录、文件和根目录列表的函数,这工作正常,但在运行文件时它显示“找不到 txt 文件”。 if not 条件使程序排除所有.DS_Store 文件。我认为问题可能是我打开文件的方式,但我不确定

       for root, directories, filenames in os.walk("Files_to_Insert"):

                   if not (filenames[-1] == ".DS_Store"):
                           lastFile = filenames[-1]
                            print lastFile

                             with open (lastFile, 'rt') as myfile: 

IOError: [Errno 2] 没有这样的文件或目录:txt 错误发生在 with open 中,因为它找不到文件。 当我打印时,我得到了所有的 txt 文件,但是我不能在“with open”中使用它们

【问题讨论】:

  • 你必须给open文件的路径,而不仅仅是文件名。
  • 我可以在“with open”中制作它还是我需要制作一个新的?我是 python 和 os 库的新手
  • with open (os.path.abspath(lastFile), 'rt') as myfile: 应该这样做。
  • 我也犯了同样的错误

标签: python-3.x logic python-import


【解决方案1】:

我使用的典型os.walk 是这样的:

import os

for root, directories, filenames in os.walk("."):
    for f in filenames:
        if f.endswith(".DS_Store"):
            continue
        print(os.path.abspath(f))
        with open (os.path.abspath(f), 'rt') as myfile:

【讨论】:

    【解决方案2】:

    我通过在单独的字符串中给出路径和文本文件来解决它:

     for root, directories, filenames in os.walk("Files_to_Insert"):
    
    
    
            if  not(filenames[-1] == ".DS_Store"):
                lastFile = filenames[-1]
                # print (lastFile)
    
                with open(str(root) + '/' + lastFile,'rt') as myfile:
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-01
      • 2022-10-03
      • 2012-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多