1

I have a text file called "test", and I would like to create a list in Python and print it. I have the following code, but it does not print a list of words; it prints the whole document in one line.

file = open("test", 'r')
lines = file.readlines()

my_list = [line.split(' , ')for line in open ("test")]
print (my_list)
3
  • 1
    You need to be a lot more specific about what you're trying to do. The code above reads the same file in two different ways, and your description lacks sufficient detail to understand what your goal is. Commented Aug 5, 2016 at 3:50
  • If your file has values separated by commas, you might want to use the CSV (comma-separated values) library built into python. Commented Aug 5, 2016 at 3:51
  • Possible duplicate of How to read a file line by line into a list with Python Commented Aug 5, 2016 at 4:25

3 Answers 3

3

You could do

my_list = open("filename.txt").readlines()
Sign up to request clarification or add additional context in comments.

Comments

2

When you do this:

file = open("test", 'r')
lines = file.readlines()

Lines is a list of lines. If you want to get a list of words for each line you can do:

list_word = []
for l in lines:
    list_word.append(l.split(" "))

1 Comment

Note that you might also want to remove the \n character before doing that, with: l = l.replace("\n","")
2

I believe you are trying to achieve something like this:

data = [word.split(',') for word in open("test", 'r').readlines()]

It would also help if you were to specify what type of text file you are trying to read as there are several modules(i.e. csv) that would produce the result in a much simpler way.

As pointed out, you may also strip a new line(depends on what line ending you are using) and you'll get something like this:

data = [word.strip('\n').split(',') for word in open("test", 'r').readlines()]

This produces a list of lines with a list of words.

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.