【问题标题】:Empty file not reading as empty in Python 3空文件在 Python 3 中不读取为空
【发布时间】:2018-08-05 01:49:56
【问题描述】:

我的程序读取了一个文件 (batch_files),该文件包含一个文件名列表,该文件名包含数据段。如果batch_files 为空,代码将创建一个新的文本文件。如果batch_files 包含文件名,程序会将数据附加到现有文件中。

这是我在 Python 3.5 中工作的原始代码/伪代码:

    with open(path + batch_files, 'r+', encoding='utf-8') as file_list:
        batch_names = [line.rstrip('\n') for line in file_list]
        series_count = len(batch_names)
        # Initialize an empty batch if none exists.
        if series_count == 0:
            series_count += 1
            Pseudo-code: create file and append file name to `batch_files`
        # Load existing batches.
        for file_name in batch_names:
            with open(path + file_name, 'r', encoding='utf-8') as tranche:
                Pseudo-code: append data to existing file.

在 Python 3.6.6 中,我收到以下错误:

PermissionError: [Errno 13] Permission denied:'[错误消息包括没有文件名的工作目录路径]'

即使batch_files 为空,即batch_names = ['']len(batch_names) 等于 1(每个调试跟踪)。然后代码跳过文件初始化子例程,因为if series_count == 0 为假。然后代码尝试加载一个不存在的数据文件,但由于file_name 中没有文本而产生错误。

我尝试了以下空列表和文件测试:

  1. if not batch_names: 这个thread
  2. if os.stat(path + batch_files).st_size == 0: 这个thread

两个版本都未能触发文件初始化。有关使这些解决方案发挥作用的更多信息,请参阅下面的编辑。 旁注:我使用 Notepad++ 来确保 batch_files 为空。文件大小为 0k。操作系统为 Windows 10。

为什么我的代码认为batch_files 不为空?你建议我如何解决这个问题?

编辑: 根据@saarrrr,该列表包含一个空文本字符串,因此我使用以下代码解决了这个问题。

首选方法:

    batch_list = [line.rstrip('\n') for line in file_list]
    # Remove empty text strings.
    batch_names = list(filter(None, batch_list))
    # Initialize an empty batch if none exists.
    if not batch_names:

或者:

    batch_list = [line.rstrip('\n') for line in file_list]
    batch_names = list(filter(None, batch_list))
    series_count = len(batch_names)
    # Initialize an empty batch if none exists.
    if series_count == 0:

另外,if os.stat(path + batch_files).st_size == 0: 也可以。这个选项最初对我来说失败了,因为我将 batch_files 指向了错误的文件。

我不明白为什么带有空文本字符串的列表不为空。我也不明白为什么我原来的条件适用于 3.5 而不是 3.6。欢迎解释问题的根源或更多pythonic解决方案。

编辑 2:Link 到标准库讨论列表。嵌套的空列表是可能的。没有提到空文本字符串;但是,我假设相同的逻辑适用于其他数据类型,即空数据类型被视为列表元素。

【问题讨论】:

  • 等一下,batch_names = [''] 表示它不是空的,它里面有一个空字符串。 batch_names = [] 为空。
  • 我认为问题是您没有读取/写入文件的权限...。您可以发布整个错误消息吗?也许只是删除您的目录路径
  • 你确定路径确实是一个文件吗?您可能正在打开一个目录,这将导致该错误。
  • @DivideByZero 你可以尝试打印'path + batch_files'并检查它是否是文件而不是目录
  • @saarrrrr -- 我认为空字符串是问题的症结所在。为什么带有空字符串的列表不注册为空?解决方案建议?

标签: python list file empty-list


【解决方案1】:

错误信息写PermissionError,表示你没有读/写文件的权限(r+模式表示读&写), 文件的内容是什么并不重要。

也正如@saarrrr 指出的那样,batch_names = [''] 意味着它里面有一个空字符串,它不是空的。 batch_names = [] 为空。

【讨论】:

  • 产生错误是因为代码试图写入一个不存在的文件。发生这种情况是因为跳过了初始化例程。
  • 当文件不存在时,我也会收到此错误消息:FileNotFoundError: [Errno 2] No such file or directory: 'foobar.txt'
  • 从我的代码中可以看出,要写入的文件是路径和文件名的串联。文件名取自 batch_names,它是空的。因此,程序会尝试写入没有附加文件名的路径。因此,我得到 Errno 13 而不是 Errno 2。
猜你喜欢
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-03
相关资源
最近更新 更多