将每个项目打印到列表中

时间:2020-09-09 14:16:48

标签: python

我有一个查找用户名并将其保存到文件的脚本。我想将accounts.txt中的用户名转换为列表。我不确定该怎么做...有人知道如何提供帮助吗?

accounts.txt

@example1
@example2
@example3
@example4
@example5
@example6

我希望我的程序从accounts.txt创建什么:

['example1', 'example2', 'example3', 'example4', 'example5', 'example6']

3 个答案:

答案 0 :(得分:1)

尝试这样的事情?

my_list = []

with open("accounts.txt", "r") as file:
    for line in file:
        my_list.extend(line.split())
my_list = [s[1:] for s in my_list]


print(my_list)

将打印以下内容:['example1', 'example2', 'example3', 'example4', 'example5', 'example6']

答案 1 :(得分:0)

使用readlines()读取文件,然后使用列表理解剥离每行:

with open("accounts.txt") as fileObj:
    content = fileObj.readlines()

# getting rid of the empty lines
file_data = [x.strip() for x in content] 

答案 2 :(得分:0)

您必须阅读每一行并删除第一个“ @”字符并添加到列表中。
尝试下面的代码

connect(mapStateToProps)(withTheme(withStyles(styles)(SearchWrapper)));

输出

with open("accounts.txt","r") as f:
    print([a[1:].strip() for a in f])