0

I need to define a function that opens a text file, reads it, then loads the entire file into a string. This is what I have so far:

def encrypt_file(filename):
    open_file = open(filename, 'r')
    file_content = filename.read()
    filename.close()

encrypt_file(filename)
user_input = input('enter file name: ')

This is the error I get:

encrypt_file(filename)
NameError: name 'filename' is not defined

What am I doing wrong here?

pushkin
  • 9,575
  • 15
  • 51
  • 95
Gabe
  • 9

3 Answers3

0

The filename var is not defined yet, you have to swap lines a little bit:

filename = input('enter file name: ')
encrypt_file(filename)

Also some intro to How To Handle Plain Text Files in Python 3 and SO question: How do I read a text file into a string variable in Python would be useful for you.

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
0

Your code won't work anyway.

def encrypt_file(filename):
    open_file = open(filename, 'r')
    file_content = open_file.read()
    open_file.close()

some_filename = input('enter file name: ')
encrypt_file(some_filename)

Best Practice:

def encrypt_file(filename):
    with open(filename, 'r') as open_file:
        file_content = open_file.read()
surge10
  • 622
  • 6
  • 18
-1

Perhaps what you want to do is:

def encrypt_file(filename):
    open_file = open(filename, 'r')
    file_content = filename.read()
    open_file.close()

filename = input('enter file name: ')
encrypt_file(filename)

Please note also the correction on the line open_file.close().

fferri
  • 18,285
  • 5
  • 46
  • 95