Python Forum
Read a data from text file (Notepad)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Read a data from text file (Notepad)
#1
Hi once again...

Edit: As previously mentioned, the notepad consists of 12 records of countries such as:

Malaysia, Kuala Lumpur
Japan, Tokyo
United States of America, Washington
Canada, Ottawa
Pakistan, Islamabad
Australia, Canberra
Mexico, Mexico City
Thailand, Bangkok
Taiwan, Taipei
China, Beijing
Czech Republic, Prague
Russia, Moscow

Thank you for helping me with the previous post.
However, right now I would like to search a COUNTRY in the text file (Notepad).
This is the best code I can think of.

print("No.\tCountries\t\t\t   Capitals")
f = open(r'C:\Users\USER\Desktop\Notepad_Read\countries.txt')
count = 0

for line in f:
    line = line.rstrip('\n')
    rec = line.split(',')
    country = rec[0]
    capital = rec[1]
    count = count + 1
    print("{0:1}\t{1:26}\t {2:24}".format(count,country,capital))


while True:
    line = str(input("Enter a country name (x to Exit):"))
    if line == 'x':
        break
    elif line == country: #Read the country name
        list = line.split(',')
        print ("The capital of {1} is {2}".format(country,capital))
        
    else:
        list = line.split(',')
        print("The country is not in the list. Please try again.")


f.close()
I want to INPUT a country name and show it out its capital.
But it wouldn't let me read the data I stored.
Please help once again...

Thank you! Doh

I changed here:

    elif line == country:
        list = line.split(',')
        print ("The capital of {0} is {1}".format(country,capital))
However, it only seems to let me read Russia, but other countries I couldn't pop out the answer.

Need Help!
Reply
#2
This is because the iterator ( 'f' is exhausted ). During the reading from a file ( the for loop ) store the line in a list or a dictionary or a set ) so you can use it later. Or you can use f.readlines() method which will create a list and iterate over the list instead of 'f'.

data = f.readlines()
for line in data:
    # ...
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
(May-18-2018, 03:47 PM)wavic Wrote: This is because the iterator ( 'f' is exhausted ). During the reading from a file ( the for loop ) store the line in a list or a dictionary or a set ) so you can use it later. Or you can use f.readlines() method which will create a list and iterate over the list instead of 'f'.
data = f.readlines() for line in data: # ...

Hi wavic!
Thanks for your reply,
As you mentioned the word "Exhausted" does that meant by "Used up the storage" right?
Therefore, would it be possible to use once again?

I used your suggestion the f.readlines() method.

However, it could not execute the "Enter a country name (x to Exit):".
Reply
#4
Post the code, please!
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
(May-18-2018, 04:24 PM)wavic Wrote: Post the code, please!

print("No.\tCountries\t\t\t   Capitals\n ")
f = open(r'C:\Users\USER\Desktop\Notepad_Read\countries.txt')
count = 0

data = f.readlines()
for line in data:
    line = line.rstrip('\n')
    rec = line.split(',')
    country = rec[0]
    capital = rec[1]
    count = count + 1
    print("{0:1}\t{1:26}\t {2:24}".format(count,country,capital))
    

while (True):        
    line = str(input("Enter a country name (x to Exit): "))
    if line == 'x':
        break
    elif line == country:
        
        print ("The capital of {0} is {1}".format(country,capital))
        
    else:
        
        print("The country is not in the list. Please try again.")
        

f.close()
It could read Russia only. Other countries it couldn't be executed...

PS: Somehow I restart the Spyder then it worked.
Reply
#6
The 'country' is set to Russia on line 9 during the last loop.
You have to traverse trough data again and to check if the input is equal to the str.startswith from each element.
I would use a dictionary but I don't know what is the exact assignment or whether you had the dictionaries at school.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#7
(May-18-2018, 04:56 PM)wavic Wrote: The 'country' is set to Russia on line 9 during the last loop. You have to traverse trough data again and to check if the input is equal to the str.startswith from each element. I would use a dictionary but I don't know what is the exact assignment or whether you had the dictionaries at school.

Okay now I noticed.
The full question would be:
Create a text file called countries to store a list of n=12 country names with their capitals. Write a program to read the same into lists country and capital respectively. Then, when the user enters a country name, the program displays the message "The capital of {Country} is {Capital}" if there is a match, or the message "The country is not in the lists" if there is no match.

Now I notice, after reading the text file, it wants to program/store into a list. Is this possible?
I Will try at the same time
Reply
#8
You have 'country' and 'capital'. Adding each of them to a corresponding list is a routine.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#9
(May-19-2018, 08:17 AM)wavic Wrote: You have 'country' and 'capital'. Adding each of them to a corresponding list is a routine.

Hi wavic!

Sorry I dont understand the "Adding each of them to a corresponding list is a routine."
Which means It cant store the whole list at once? But only store line by line?

(May-18-2018, 04:56 PM)wavic Wrote: The 'country' is set to Russia on line 9 during the last loop. You have to traverse trough data again and to check if the input is equal to the str.startswith from each element. I would use a dictionary but I don't know what is the exact assignment or whether you had the dictionaries at school.

May I know how to traverse the data again?
Is there any code for it?

Sorry for not understanding well.
Reply
#10
>>> l = list('some data')
>>> for element in l:
...     print(element)
... 
s
o
m
e
 
d
a
t
a
>>> for element in l:
...     print(element*4)
... 
ssss
oooo
mmmm
eeee
    
dddd
aaaa
tttt
aaaa
Here I loop again through the list to do something else.


As I understand the assignment you have to have one list for the countries and one to store the capitals. But this is the mine interpretation.
Quote:... to read the same into lists country and capital respectively
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Exclamation URGENT: How to plot data from text file. Trying to recreate plots from MATLAB JamieAl 4 3,533 Dec-03-2023, 06:56 AM
Last Post: Pedroski55
  computer science coursework, read the text please and tell me if theres any specifics sixcray 4 2,604 Nov-11-2020, 03:17 PM
Last Post: buran
  Can we store value in file if we open file in read mode? prasanthbab1234 3 2,545 Sep-26-2020, 12:10 PM
Last Post: ibreeden
  Working with text data APK 4 2,477 Aug-22-2020, 04:48 AM
Last Post: buran
  [split] how to read a specific row in CSV file ? laxmipython 2 8,853 May-22-2020, 12:19 PM
Last Post: Larz60+
  Read data from a CSV file in S3 bucket and store it in a dictionary in python Rupini 3 6,963 May-15-2020, 04:57 PM
Last Post: snippsat
  Read text file, process data and print specific output Happythankyoumoreplease 3 2,902 Feb-20-2020, 12:19 PM
Last Post: jefsummers
  Convert text from an image to a text file Evil_Patrick 5 4,262 Jul-30-2019, 07:57 PM
Last Post: DeaD_EyE
  read from file mcgrim 16 6,080 May-14-2019, 10:31 AM
Last Post: mcgrim
  reading text file and writing to an output file precedded by line numbers kannan 7 10,365 Dec-11-2018, 02:19 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020