TC1111
TC1111

Reputation: 89

Python input function and read file

The below code block returns the data I want, however I have called 'read_from_file(filename) from outside the if statement, where filename doesn't exist.

I know I have two options to improve this:

  1. call read_from_file(filename) from inside my if statement, or
  2. make filename a global variable.

However when I attempt both I run into other issues such as the text from the file not returning. Would someone be able to show the correct way to do one of the above options?

filename = input('input the filename: ')
#read the file
def read_from_file(filename):
    content = []
    with open(filename, "r") as file:
        for line in file:
            line = line.strip()
            if "-" not in line:
                content.append(float(line))
    return content

print(read_from_file(filename))

Upvotes: 1

Views: 707

Answers (1)

Guy
Guy

Reputation: 50819

You can remove the file_name parameter from read_from_file and get the file name from inside the function

def read_from_file():
    filename = input('input the filename: ')

print(read_from_file())

Upvotes: 2

Related Questions