空文件在Python 3中读取为空

时间:2018-08-05 01:49:57

标签: python list file empty-list

我的程序读取一个文件(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]权限被拒绝:'[错误消息包括不带文件名的工作目录路径]'

即使batch_files为空,即batch_names = ['']len(batch_names)等于1(每个调试跟踪)。然后,代码将跳过文件初始化子例程,因为if series_count == 0为false。然后,代码尝试加载不存在的数据文件,但由于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到标准库讨论列表。嵌套的空列表是可能的。没有提到空文本字符串;但是,我假设其他数据类型使用相同的逻辑,即空数据类型被视为列表元素。

1 个答案:

答案 0 :(得分:0)

错误消息写为PermissionError,这意味着您无权读取/写入文件(r+模式是指读写), 不管文件的内容是什么。

也正如@saarrrr所指出的,batch_names = ['']表示其中包含一个空字符串,该字符串不为空。 batch_names = []为空。