How to get latitude and longitude of place based on specific country?

I am working on project to get latitude and longitude of specific place but the result is incorrect because the place i want in ‘x country’ is the same name in ‘y country’. I want to add country attribute to search result.

I am using this code:

from geopy.geocoders import Nominatim

with open('C:/Users/UI UX/Desktop/test.txt') as f:
    lines = f.readlines()

# print(lines)

for line in lines:
    print(line.replace('n', ''))
    geolocator = Nominatim(user_agent="my_user_agent")
    loc = geolocator.geocode(line)
    print("latitude is :", loc.latitude, "nlongtitude is:", loc.longitude)
    # print(loc.raw)
    print('Location Address: ' + loc.address)
    print('---------------------------------------------------')

Any kind of help please?

Answer

In your geocode request you can specify a list of countries with this syntax: geocode(countries = your_list). The countries can be specified by two letter country codes (ISO 3166-1).

See geopy documentation here and list of country codes here.

For example

mycountries = [US,]
loc = geolocator.geocode(line, countries = mycountries)