1

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.'] 

2 Answers 2

3

You can do:

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

i.e. 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] 
Sign up to request clarification or add additional context in comments.

1 Comment

thank you, but how do I make each word a string? This is the output I am hoping for: [ ['Das','ist','1e'], ['Textdatei.'] ]
1

Here's a one-liner for that.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.