0

I am having trouble trying to figure out how to import text from a text file easily or at least a memorable method. I am trying to make a program that insults the user (for school), that brings in a word/s from one text file, adds another word/s from the second file and the final word/s from the third text file...

I am having trouble finding a way of coding to do this...I have the random number up and running to pick the text I just need to know how to access strings or text in a text file.

4
  • text = open("file.txt").read() perhaps? Commented Oct 18, 2012 at 15:04
  • How large are the textfiles? If it's a relatively small list of insults, you could just store the data in lists ... Commented Oct 18, 2012 at 15:06
  • The text files are not that big...about 50 words, but our teacher asked to import them from external text-files and he is reluctant to teach us. Commented Oct 18, 2012 at 15:07
  • 1
    Also, be careful saying import -- import is a statement that executes python code (unless it was already imported) and assigning the "result" to a namespace. Commented Oct 18, 2012 at 15:08

1 Answer 1

1

The easiest way is to use the with statement. It takes care of closing the file for you.

with open("file.txt") as f:
    for line in f:
        # do something with line

Or read the data into directly into a list:

with open("file.txt") as f:
    lines = list(f)
# do something with lines
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.