Hey people, I've got a file, looks like this:

england
america
spain
brazil
germany
australia

now, I need to read it line by line:

country = open('languages/country.lang', 'r')

and give a value to it, like:

A1 = country.readline()

and then A2 for the next country and so on. So I was thinking , how can I possibly do this, without needing to have a big list like:

A1 = country.readline()
A2 = country.readline()
A3 = country.readline()
A4 = country.readline()
A5 = country.readline()
A6 = country.readline()

I could use "for" or "while", i guess, but I'm not sure how. Any ideas? Thanks

Recommended Answers

All 12 Replies

languagelist = open('languages/country.lang').read().split() gets you words of file language as which you access by index 0 for first until length of list-1. So for example languagelist[2] would be third one spain.

About the cycle.

countries = open('languages/country.lang', 'r').readlines()
for i in range (0, len(countries):
    vars()['A%s' % i + 1] = countries[i]

thanks you very much again. Youre like a god ;)

Not a very good approach, since your variable names A1, A2, ... are rather meaningless.

I also thought of that, but that's what he asks.

Also there is the question of newlines

countries="""england
america
spain
brazil
germany
australia """

open('countries.lang','w').write(countries)
print repr(open('countries.lang').readline())
print('By reading from generator also:')
for lang in open('countries.lang'):
    print(repr(lang))

print('Split takes care of newlines simply for no white space list')
print(open('countries.lang').read().split())
"""output:
'england\n'
By reading from generator also:
'england\n'
'america\n'
'spain\n'
'brazil\n'
'germany\n'
'australia '
Split takes care of newlines simply for no white space list
['england', 'america', 'spain', 'brazil', 'germany', 'australia']
"""

However this is little dangerous, as some language could contain multiple words, then best would be:

print('Safest way')
print([lang.rstrip() for lang in open('countries.lang')])
print('Safest way')
print([lang.rstrip() for lang in open('countries.lang')])

This just prints on the screan, but i realised , that countries like South Africa it comes out like:

South
Africa

When I do, "print([lang.rstrip() for lang in open('countries.lang')])" it does basically what i what, because it devides the country name by line, but how can a get the value, lets suppose, South Africa.

Thank you everyone, and Beat_Slayer, I also tried what you said, but it doesn't work properlly, maybe its just me, LOL, thanks for trying to help anyway ;) Any ideas, for my new problem?

For this i think a dictionary approach is most natural.
@Beat_Slayer test your code.

Edit:

lets suppose, South Africa.

South Africa work fine in mine code.
A7 is South Africa

countries = [i.strip() for i in open('countries.txt')]
#Bad variables list
var_list = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6']

countries_Dict = dict(zip(var_list, countries))
print (countries_Dict)

#Iterate over Dict
for k,v in countries_Dict.items():
    print ('%s is %s' % (k, v))

'''Out-->
{'A1': 'england', 'A3': 'spain', 'A2': 'america', 'A5': 'germany', 'A4': 'brazil', 
A1 is england
A3 is spain
A2 is america
A5 is germany
A4 is brazil
A6 is australia
'''

As tony suggested, a list might be the way to go. Let's play ...

# let's assume this is the data string you get from
# data = open('languages/country.lang', 'r').read()
data = """\
england
america
spain
brazil
germany
australia
south africa"""

# make a list of countries
countries = []
for country in data.split('\n'):
    countries.append(country)

import pprint
pprint.pprint(countries)
"""
['england',
 'america',
 'spain',
 'brazil',
 'germany',
 'australia',
 'south africa']
"""

# with a list you can at list do something like this ...
print('spain' in countries)       # True
print(countries.index('brazil'))  # 3
print(countries[3])             # brazil
print(countries[5:])            # ['australia', 'south africa']

for country in countries:
    if country.startswith('s'):
        print(country)
"""
spain
south africa
"""

Hey vagaseat. Thanks for that new way to do this, but I guess i found something quicker, tell me if this is not the right way of doing it. So, instead of:

languagelist = open('languages/country.lang').read().split()
languagelist[1]

I found "splitlines()" ;) and it works perfectly.

languagelist = open('languages/country.lang').read().splitlines()
languagelist[1]

Is there any problems, in doing this way? Thanks for the ideas everyone. I will mark this thread as solved but i still want opinions :)

If you read from a file, then using splitlines() is a very good solution. Nice discovery! Python is such a full featured language, it pays to read the manual.

Basically it is same as using split('\n') but more readable. Golden RTFM medal for you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.