简体   繁体   English

使用python将文件中的字符串导入列表

[英]Importing strings from a file, into a list, using python

I have a txt file, with these contents: 我有一个txt文件,其中包含以下内容:

a,b
c,d
e,f
g,h
i,j
k,l

And i am putting them into a list, using these lines: 我使用以下几行将它们放入列表中:

keywords=[]
solutions=[]
for i in file:
    keywords.append((i.split(","))[0])
    solutions.append(((i.split(","))[1]))

but when I print() the solutions, here is what it displays: 但是当我打印()解决方案时,它显示的是:

['b\n', 'd\n', 'f\n', 'h\n', 'j\n', 'l']

How do I make it, so that the \\ns are removed from the ends of the first 5 elements, bu the last element is left unaltered, using as few lines as possible. 我如何做到这一点,以便从前5个元素的末尾除去\\ ns,使最后一个元素保持不变,并使用尽可能少的行。

You can use str.strip() in order to trimming the last whitespace. 您可以使用str.strip()来修剪最后一个空格。 But as a more pythonic approach you better to use csv module for loading your file content which will accept a delimiter and return an iterable contain tuples of separated items (here, the characters). 但是,作为一种更具Python风格的方法,您最好使用csv模块加载文件内容,该文件内容将接受定界符并返回可迭代的包含分隔项(此处为字符)的元组。 The use zip() function to get the columns. 使用zip()函数获取列。

import csv
with open(file_name) as f:
    reader_obj = csv.reader(f, delimiter=',') # here passing the delimiter is optional because by default it will consider comma as delimiter.
    first_column, second_column = zip(*reader_obj)

You need to string.strip() the whitespace/new-line characters from the string after reading it to remove the \\n : 您需要在读取字符串后从字符串中将string.strip()的空格/换行符删除以删除\\n

keywords=[]
solutions=[]
for i_raw in file:
    i = i_raw.strip() # <-- removes extraneous spaces from start/end of string 
    keywords.append((i.split(","))[0])
    solutions.append(((i.split(","))[1]))

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

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