0

I have a names and numbers in my file (name of the file 'phone_book') and I tried to read all data using this code:

def read_phonebook():
    read = open("phone_book.txt", 'r')
    i = 0
    for i in (len(read)):
        print(i + '\t')

    read.close()

while True:
if menu == 2:
    read_phonebook()

but it gives Error: read_phonebook file has no len()

If I don't use len it keeps printing data because I'm using While loop. Could someone explain me how can I make this function to read list's whole data? with using While Loop?

  • 2
    https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files tells you all you need - it even comes with code examples... – Patrick Artner Jun 02 '18 at 17:23
  • 1
    Why are you using a while loop to read a file? What is `menu`? Why do you set `i = 0` if the next command overwrites it? Why are you expecting `len` to give you an iterable? It would help you to make a [MCVE]. – wjandrea Jun 02 '18 at 17:52
  • If you wanted to loop over the length of anything, it would be `for i in range(len(read)):`... But `read` here is an iterable object, so using `len()` would actually iterate the entire thing before you printed each line, and you're left with a fully consumed iterable, meaning nothing can be printed after – OneCricketeer Jun 02 '18 at 19:58

2 Answers2

4

Read the tutorials first.

  • if you are reading file defining a function isn't necessary.
  • learn basics first
  • if you are just reading file and you are a beginner in programming, you are taking a complicated approach.
  • take a simple approach and that helps you comprehend the input, output and ultimate goal.

Here is a quick tips for beginner and the simplest way of reading a file in python.

with open("phone_book.txt") as mytxt:
    for line in mytxt:
        print (line)

        Or do something with line

        # if you want to split the line
        # assuming data is tab separated
        newline = line.rstrip("\n").split("\t")

        # if you want conditional printing
        if len(line) > 0:
            print(line)

Lessons:

  • when you with open ... file will auto close at the end when it comes out of that scope.
  • using for line with out doing .read() prevents you from loading all the data on the memory.
  • fix your indentation issues
everestial007
  • 6,665
  • 7
  • 32
  • 72
0

Here, each line can be iterated on read.

def read_phonebook():
    read = open("phone_book.txt", 'r')
    i = 0
    for line in read:
        print(line)

    read.close() 
Rahul Goswami
  • 535
  • 3
  • 14