Damon Daxtor
Damon Daxtor

Reputation: 25

Avoid white space when reading a file

I am trying to read a list of coordinates from a text file and insert it into a url

Here is my code:

with open("coords.txt", "r") as txtFile:
for line in txtFile:
    coords = line
    url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + coords + '&radius=1&key=' + key
    json_obj = urllib2.urlopen(url)
    data = json.load(json_obj)
    print data['results']

When I run it, I get this error:

Traceback (most recent call last):
  File "C:\Users\Vel0city\Desktop\Coding\Python\placeid.py", line 8, in     <module>
    json_obj = urllib2.urlopen(url)
  File "C:\Python27\lib\urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 429, in open
    req = meth(req)
  File "C:\Python27\lib\urllib2.py", line 1125, in do_request_
    raise URLError('no host given')
URLError: <urlopen error no host given>

I am pretty sure this is due to the fact that python inserts a line break for every line in a text file so when I print out the final url with the coords concatenated to it, i get this:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.773972,-122.431297
&radius=1&key=
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.773972,-122.431297
&radius=1&key=
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.773972,-122.431297
&radius=1&key=
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.773972,-122.431297&radius=1&key=

how would i remove this linebreak so it doesnt screw up the url?

Upvotes: 1

Views: 98

Answers (1)

omri_saadon
omri_saadon

Reputation: 10661

You can use the strip method

coords = line.strip()

strip does nothing but, removes the the whitespace in your string.

You can use rstrip and lstrip if you would like to strip only one side of the line

EDIT:

As TemporalWolf mentioned in the comments, the strip method can be used to strip other things beside whitespace (which is the default).

For example, line.strip('0') would removes all '0' occurrences.

Upvotes: 2

Related Questions