Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Sep 2010
    Posts
    65
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Opening and reading a text file

    I am a relatively new beginner trying to learn Python and been trying to open and read an ordinary text file from the command line.

    I open a terminal and type python and then at the prompt i type:

    Code:
    text_file = open("filename.py", "r")
    text_file.close()
    Would someone please show me where i am going wrong please. Thanks

  • #2
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,076
    Thanks
    23
    Thanked 592 Times in 591 Posts
    You have opened a file and closed a file, you never read the file.
    Code:
    output = text_file.read()
    puts the file in variable output.

    FYI, I hate doing things in the command line. If you rather have a GUI try IDLE. It free and nice when your starting out.
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."

  • #3
    Regular Coder Samhain13's Avatar
    Join Date
    Aug 2008
    Location
    Pilipinas
    Posts
    169
    Thanks
    4
    Thanked 18 Times in 18 Posts
    I heard this way is better:
    Code:
    with open("path_to_file") as f:
        text_file = f.read()
    I am a Man of Truth. I am a Free Human Person. I am a Peacemaker.
    ** Independent Multimedia Artist in Pasig **


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •