简体   繁体   中英

How to split strings in lists

I have a text in a file with multiple lines. I would like to create one big list, with each line as a seperate list inside. Within these lists each word should be a string. This is my code at the moment, I am failling to split the strings within the lists.

f = open("test.txt","r")

for line in f.readlines():
line2= line.split(",")
print(line2)

f.close()

This is the output:

['Das ist 1e\n']
['Textdatei', '\n']
['bestehend aus mehreren Wörtern.']

You can do:

with open('file.txt') as f:
    out = [line.rstrip('\n').split(',') for line in f]

ie iterate over the lines of the file object (which is an iterator ), strip off the newline at the end and split the line on comma.

Note that, if you want to strip off whitespaces from both start and end, use line.strip() instead. Also, the file would be opened in rt (read-text) mode by default, so you can drop the explicit declaration of the mode parameter, if you want.


Edit:

It seems you have space separated words, in that case use split() :

with open('file.txt') as f:
    out = [line.rstrip('\n').split() for line in f]

这是一线的。

[line.split(',') for line in Path('test.txt').open('r').read().split('\n')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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