1

Im learning Python 3 and I've got stuck while writing a program.

Im trying to write some code that will read a file, then print out a slice of its text. Here's what I have so far.

def greeting():
 """Print a message when the program starts."""
 greeting = "Welcome to the file reader."
 greeting += "\nEnter the name of the file you would like to read. "
 greeting += "If the file is in a different folder, type the file path."
 greeting += "\n(Type 'exit' to quit, or 'help' for help.) "
 file_name = input(greeting)
def read_file():
 """Search for the file, then read it line by line. Print an error if the file isn't found."""
 try:
 with open(file_name) as f_obj:
 file_contents = f_obj.readlines()
 print(file_name + " was opened successfully")
 except FileNotFoundError:
 print("Error: File not found.")
greeting()
read_file()
print(file_contents[:9])

When i run this code, I enter a filename (of a text file in the same directory) and I get this error.

Traceback (most recent call last):
 File "reader.py", line 21, in <module>
 read_file()
 File "reader.py", line 13, in read_file
 with open(file_name) as f_obj:
NameError: name 'file_name' is not defined

So my question is, how do I properly store user input in a function and then call it in another function?

glibdud
7,9704 gold badges32 silver badges38 bronze badges
asked Mar 1, 2019 at 15:14

2 Answers 2

2

What you want to do is not store the input in the local scope of the function (this is counter intuitive) because you need the data elsewhere (other functions).

You should return the data from your greeting() function so that it can be used in other logic, like so:

def greeting():
 """Print a message when the program starts."""
 greeting = "Welcome to the file reader."
 greeting += "\nEnter the name of the file you would like to read. "
 greeting += "If the file is in a different folder, type the file path."
 greeting += "\n(Type 'exit' to quit, or 'help' for help.) "
 file_name = input(greeting)
 return file_name # Return user input
def read_file(file_name):
 """Search for the file, then read it line by line. Print an error if the file isn't found."""
 try:
 with open(file_name) as f_obj:
 file_contents = f_obj.readlines()
 print(file_name + " was opened successfully")
 return file_contents # Return the contents of the file
 except FileNotFoundError:
 print("Error: File not found.")
input_file_name = greeting()
output_file_contents = read_file(input_file_name)
print(output_file_contents[:9])

Note: This code will have issues if the file is not found. It will reach the final print line in the script and fail because there is no output from the previous function call if the file does not exist.

answered Mar 1, 2019 at 15:18
Sign up to request clarification or add additional context in comments.

Comments

0

def greeting():
 """Print a message when the program starts."""
 greeting = "Welcome to the file reader."
 greeting += "\nEnter the name of the file you would like to read. "
 greeting += "If the file is in a different folder, type the file path."
 greeting += "\n(Type 'exit' to quit, or 'help' for help.) "
 return input(greeting)
def read_file(file_name):
 """Search for the file, then read it line by line. Print an error if the file isn't found."""
 try:
 with open(file_name) as f_obj:
 file_contents = f_obj.readlines()
 print(file_name + " was opened successfully")
 return file_contents 
 except FileNotFoundError:
 print("Error: File not found.")
print(read_file(greeting())[:9])
answered Mar 1, 2019 at 15:18

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.