How to read a file with input() in Python 3

14,362

file is a string denoting a filename when it comes out of the input function, and it remains a string. So when you iterate over it, you get the letters of the filename one by one. When you call open(file) that returns an object that can be iterated over to provide file content, but you are not currently giving that object a name or re-using it. You really mean something like:

file_name = input('Enter file name:')
file_handle = open(file_name)   # this doesn't change file_name, but it does output something new (let's call that file_handle)
for line in file_handle:
    ....
file_handle.close()

...although the more idiomatic, Pythonic way is to use a with statement:

file_name = input('Enter file name:')
with open(file_name) as file_handle:
    for line in file_handle:
        ....
# and then you don't have to worry about closing the file at the end (or about whether it has been left open if an exception occurs)

Note that the variable file_handle is an object whose class is called file (which is one of the reasons I've changed the variable names here).

Share:
14,362

Related videos on Youtube

Baruch Elias
Author by

Baruch Elias

Updated on September 15, 2022

Comments

  • Baruch Elias
    Baruch Elias over 1 year

    I have a simple program which looks through a file, finds any numbers inside, and adds them up into a variable called running_total. My issue seems to be that my file name is the thing that is being read instead of its contents.

    import re
    
    file = input('Enter file name:')
    open(file)
    print(file)
    running_total = None
    
    for line in file:
        line = line.rstrip()
        numbers = re.findall("[0-9]+", line)
        print(numbers)
        for number in numbers:
            running_total += float(number)
    
    print(running_total)
    

    What am I missing?

    • Paul Rooney
      Paul Rooney almost 7 years
      you need to capture the return from open. It returns a file object, despite its name file is just a string. You will also need to ensure the file is closed after you have used it. running_total = None is wrong, it should be running_total = 0. The values are not interchangeable, adding to None is not a valid operation.
    • juanpa.arrivillaga
      juanpa.arrivillaga almost 7 years
      Start here
  • OneCricketeer
    OneCricketeer almost 7 years
    I think you still have to worry about exceptions. The file might not exist, or permissions disallow opening
  • jez
    jez almost 7 years
    @cricket_007 clarified
  • Casey Kuball
    Casey Kuball almost 7 years
    I would do with open(file) as ..., or at the very least put the resulting File object into a variable, so that you can cleanup after (file.close()).
  • OneCricketeer
    OneCricketeer almost 7 years
    You're reading the whole filename into the memory needlessly here
  • Superspork
    Superspork almost 7 years
    I may be getting confused by the term filename. Wouldn't you need the filename?
  • OneCricketeer
    OneCricketeer almost 7 years
    Sorry... autocomplete. The whole file... And for line in file, is actually not a line at all, but a character
  • Superspork
    Superspork almost 7 years
    @cricket_007 That makes more sense. Thank you. Sorry, I thought I missed something with filename. You can instead use list comprehension to do away with loading the entire file and it would work. As for line in file, yes it iterates through the characters. My code will only add individual character numbers together. If it is larger than 9, it doesn't work and your regex version is more suitable. Depends on purpose
  • OneCricketeer
    OneCricketeer almost 7 years
    The regex version isn't mine. It was what the question used. So 100 + 1 is much different answer than 1+0+0+1.