2

I am receiving an XML response from an API in a variable r so that:

print r.read() 

displays the entire XML response.

I need to take the first line of this response and convert it to a string variable for use in a loop after some substringing. What is the best way to capture just the first line?

3
  • Wouldn't r.read() give you the whole string, which you could split by line breaks? (I never used python but I expect you could loop through each character until you reach a line break character if you must...) Commented Oct 15, 2011 at 15:43
  • I think thats a good idea. The whole response is well over 100 lines so I thought taking the first line would be simpler. Am I mistaken? Commented Oct 15, 2011 at 16:14
  • The API call returns the whole XML, unless it's giving you the string as a stream, so internally you're processing the whole 100 lines anyways, but chown's solution is less work on your part (although run-time would be the same). Commented Oct 15, 2011 at 16:29

1 Answer 1

4

r.readline()

Built-in Types - File Objects:

file.readline([size])
Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. When size is not 0, an empty string is returned only when EOF is encountered immediately.

   r.readline()
   'This is the first line of the file.\n'
   r.readline()
   'Second line of the file\n'
   r.readline()
   ''
Sign up to request clarification or add additional context in comments.

7 Comments

Yes, that is what I thought also. I did try 'print r.readline()' but I got a UnicodeDecodeError: and thought that would not work. Here is the whole thing. UnicodeDecodeError: 'ascii', '\xef\xbb\xbf<list Action="Query" pageNumber="1" pageCount="213" pageRecordCount="100" totalRecordCount="21208" xmlns="site.com/API/Gateway">\r\n', 0, 1, 'ordinal not in range(128)'
Do I need to add some conversion? Also, how do I assign r.readline() to a variable for further use? resp = r.readline()?
Yea, line1 = r.readline() would do it. You also may need to decode/encode the returned string before printing it. See docs.python.org/howto/unicode.html and doughellmann.com/PyMOTW/codecs. Or try opening the file with codecs.open(filename, encoding="utf-8", ..).
Thanks for the advice. I'll go through that and give it a shot.
Can I use the codec on the object containing the complete XML response? That way I can do it without writing it to a file. Sorry if this is a super obvious answer
|

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.