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 4 of 4
  1. #1
    New Coder
    Join Date
    Sep 2010
    Posts
    67
    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,719
    Thanks
    25
    Thanked 662 Times in 661 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 **

  • #4
    New Coder
    Join Date
    Sep 2014
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts
    The following modes are help to you for participating the Text file function
    r Open a file for read only. File pointer starts at the beginning of the file
    w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
    a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
    x Creates a new file for write only. Returns FALSE and an error if file already exists
    r+ Open a file for read/write. File pointer starts at the beginning of the file
    w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
    a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
    x+ Creates a new file for read/write. Returns


  •  

    Posting Permissions

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