简体   繁体   English

将文本文件读入列表列表,不带额外的空格或 '\n'

[英]Read text file into list of list without extra white space or '\n'

I'm trying to read a text file into a list of list.我正在尝试将文本文件读入列表列表。 When it reads the list, which has words separated by commas, the list has '' and '\n' at the end.当它读取由逗号分隔的单词的列表时,列表末尾有 '' 和 '\n'。 I've added strip() but it only removes the '\n'.我添加了 strip() 但它只删除了 '\n'。

    with open("tasks.txt",'r') as file:
    for line in file:
        word = line.strip().split(',')
        if word[0] == username:             
            view_list.append(word)

The loop works except that at the end of the list it adds: , ''循环有效,只是在列表的末尾添加了:, ''

Text file has lines of text as follows:文本文件具有如下文本行:

admin, Register Users , Use taskManager, 10 Oct 2019,25 October 2021,No,

admin, Assign initial tasks, Use taskManager.py to appropriate tasks, 10 Oct 2019, 25 Oct 2019, No,

Output: Output:

在此处输入图像描述

You have a comma after the last word so it will always append to the list the word after that comma.您在最后一个单词之后有一个逗号,因此它始终是 append 以列出该逗号之后的单词。 Maybe if you try to check if the last word is empty it doesnt append to the list.也许如果您尝试检查最后一个单词是否为空,则列表中没有 append。

Like:喜欢:

if word[0] == username and word != '':             
        view_list.append(word)

split(separator, maxsplit)拆分(分隔符,最大拆分)

Seperator - Optional.分隔符 - 可选。 Specifies the separator to use when splitting the string.指定拆分字符串时要使用的分隔符。 By default any whitespace is a separator默认情况下,任何空格都是分隔符

Maxsplit - Optional. Maxsplit - 可选。 Specifies how many splits to do.指定要进行多少次拆分。 Default value is -1, which is "all occurrences"默认值为 -1,即“所有出现”

Maybe you can try use the maxsplit in someway.也许您可以尝试以某种方式使用 maxsplit。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM