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)
zondo
  • 19,901
  • 8
  • 44
  • 83
Beginner user
  • 27
  • 1
  • 2
  • 4
  • 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. – ShadowRanger Aug 05 '16 at 03:50
  • If your file has values separated by commas, you might want to use the CSV (comma-separated values) library built into python. – BSL-5 Aug 05 '16 at 03:51
  • Possible duplicate of [How to read a file line by line into a list with Python](http://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list-with-python) – Mahdi Aug 05 '16 at 04:25

3 Answers3

3

You could do

my_list = open("filename.txt").readlines()
thesonyman101
  • 791
  • 7
  • 16
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(" "))
Michel
  • 133
  • 1
  • 8
  • 1
    Note that you might also want to remove the \n character before doing that, with: l = l.replace("\n","") – Michel Aug 05 '16 at 04:00
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.

Eduard
  • 666
  • 1
  • 8
  • 25