Slurping All Content of a File into a Variable

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Wijaya Edward

    #1

    Slurping All Content of a File into a Variable


    Hi,

    How can we slurp content of a single file
    into one variable?

    I tried this:
    >>myfile_conten t = open('somefile. txt')
    >>print myfile_content,
    <open file 'somefile.txt', mode 'r' at 0xb7f532e0>
    >>>
    But it doesn't print the content of the file.

    Regards,
    -- Edward WIJAYA
    SINGAPORE


    ------------ Institute For Infocomm Research - Disclaimer -------------
    This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you.
    --------------------------------------------------------
  • marc.wyburn@googlemail.com

    #2
    Re: Slurping All Content of a File into a Variable

    myfile_content is an object and you have only opened the file. Python
    doesn't yet know whether you want to read it, copy it etc.

    to read it try

    text = myfile_content. readlines()
    print text

    this should be in most tutorials


    Wijaya Edward wrote:
    Hi,
    >
    How can we slurp content of a single file
    into one variable?
    >
    I tried this:
    >
    >myfile_conte nt = open('somefile. txt')
    >print myfile_content,
    <open file 'somefile.txt', mode 'r' at 0xb7f532e0>
    >>
    >
    But it doesn't print the content of the file.
    >
    Regards,
    -- Edward WIJAYA
    SINGAPORE
    >
    >
    ------------ Institute For Infocomm Research - Disclaimer -------------
    This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you.
    --------------------------------------------------------

    Comment

    • Paul McGuire

      #3
      Re: Slurping All Content of a File into a Variable

      <marc.wyburn@go oglemail.comwro te in message
      news:1161948531 .098283.162950@ b28g2000cwb.goo glegroups.com.. .
      myfile_content is an object and you have only opened the file. Python
      doesn't yet know whether you want to read it, copy it etc.
      >
      to read it try
      >
      text = myfile_content. readlines()
      print text
      >
      this should be in most tutorials
      >
      readlines() will give you the file content as a list of newline-terminated
      strings. If you just want the whole file in one big string do:

      text = myfile_content. read()

      And, yes, you should wade through some of the tutorials, this is basic
      material.

      -- Paul


      Comment

      Working...