Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through words of a file in Python

Tags:

python

file

io

I need to iterate through the words of a large file, which consists of a single, long long line. I am aware of methods iterating through the file line by line, however they are not applicable in my case, because of its single line structure.

Any alternatives?

like image 689
pavlogiannis Avatar asked Oct 12 '11 19:10

pavlogiannis


1 Answers

It really depends on your definition of word. But try this:

f = file("your-filename-here").read()
for word in f.split():
    # do something with word
    print word

This will use whitespace characters as word boundaries.

Of course, remember to properly open and close the file, this is just a quick example.

like image 58
Andrea Spadaccini Avatar answered Sep 21 '22 20:09

Andrea Spadaccini