0

I'm trying to write a function that takes a filename as its argument and returns a string with all \n characters replaced by the _ character.

This is what I did:

def replace_space(filename):
    wordfile = open(filename)
    text_str = wordfile.read()
    wordfile.close()
    text_str.replace("\n", "_")

replace_space("words.txt")

I also tried using " " instead of "\n":

    text_str.replace(" ", "_")
gmds
  • 19,325
  • 4
  • 32
  • 58
puppyonkik
  • 213
  • 1
  • 7

3 Answers3

7

Python, unlike languages such as Haskell and Scala, will return None if it reaches the end of a function body without an explicit return statement. Therefore, you want this:

def replace_space(filename):
    with open(filename) as wordfile:
        text_str = wordfile.read()

    return text_str.replace("\n", "_")

Note also the use of with in place of open and close; it ensures your file gets closed even if you get an exception somewhere along the way.

gmds
  • 19,325
  • 4
  • 32
  • 58
  • Is there a way to do this without using with? curious. – puppyonkik May 28 '19 at 05:45
  • 1
    @puppyonkik `with` is basically syntactic sugar for `try-finally`; see [this answer](https://stackoverflow.com/questions/56050594/resource-aquisition-is-initialization-in-python/56050631#56050631) of mine. – gmds May 28 '19 at 05:49
  • But since `text_str` is defined inside of the `with`, won't it give a NameError on return if it can't open the file because it is trying to return a variable that is not defined? – funie200 May 28 '19 at 06:29
  • @funie200 No, because if `open` can't open the file, then it will itself raise an exception, so you won't even get to the `return`. – gmds May 28 '19 at 06:39
4

Some suggestions for your code

  • You can use with context manager to open your file which will take care of closing the file for you
  • You need return back the updated string.
def replace_space(filename):
    text_str = ''
    #Open the file and read the contents
    with open(filename) as wordfile:
        text_str = wordfile.read()

    #Replace and return the updated string
    return text_str.replace("\n", "_")

replace_space("file.txt")

If you don't want to use the context manager, you need to explicitly open and close the file like you were doing before

def replace_space(filename):
    text_str = ''

    #Open the file
    wordfile = open(filename)
    #Do the read and replace
    text_str = wordfile.read().replace("\n", "_")

    #Close file and return updated string
    wordfile.close()
    return text_str

replace_space("file.txt")
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0
def replace(filename):
    with open(filename, 'r') as file:
        text = file.read()
    text = text.replace('\n', '_')
    return text
Divyanshu Srivastava
  • 1,379
  • 11
  • 24