2 Replies - 11527 Views - Last Post: 01 March 2010 - 11:35 AM Rate Topic: -----

#1 Guest_gretty*


Reputation:

[Python] Read File Display Each word on line

Posted 28 February 2010 - 11:53 PM

Hello

I am learning Python & I am trying to read a text file, store each word in the file in a list or turple(which would be better?) then output/print each word on a new line.

I cannot seem separate the file contents by words. Also I am sure I am not using a for loop to display the contents of a list and/or turple correctly.

Any suggestions would be very helpful

file = open('data.txt,'r')

fileContent = file.read()

# go through each element of fileContent & separate the strings into words
for word in range(fileContent):
    fileContent[word].split()

# print each word(element) in the list fileContent on a different line
for words in range(fileContent):
    print fileContent[words]

file.close()



Is This A Good Question/Topic? 0

Replies To: [Python] Read File Display Each word on line

#2 girasquid  Icon User is offline

  • Barbarbar
  • member icon

Reputation: 108
  • View blog
  • Posts: 1,825
  • Joined: 03-October 06

Re: [Python] Read File Display Each word on line

Posted 01 March 2010 - 11:19 AM

Generally words are separated by spaces, right? Try reading your file line-by-line using readline() instead of read(), and splitting each line on ' '.
Was This Post Helpful? -1
  • +
  • -

#3 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5829
  • View blog
  • Posts: 12,683
  • Joined: 16-October 07

Re: [Python] Read File Display Each word on line

Posted 01 March 2010 - 11:35 AM

View Postgirasquid, on 01 March 2010 - 12:19 PM, said:

Generally words are separated by spaces, right?


A new line is also whitespace. You're both making this too hard.

This should work:
file = open('data.txt,'r')
fileContent = file.read()
for word in fileContent.split():
	print word


Was This Post Helpful? 1
  • +
  • -

Page 1 of 1