2

This is my function:

def read_text():
    quotes = open("C:\blop\movie_quotes.txt")
    contents_of_file = quotes.read
    print(contents_of_file)
    quotes.close
read_text()

I am just trying to read a file and print the text within the file, but I get this error:

Traceback (most recent call last):File "C:/Python27/detect_profanity.py", line 6, in <module>
read_text()File "C:/Python27/detect_profanity.py", line 2, in read_text
quotes = open("C:\blop\movie_quotes.txt")
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\x08lop\\movie_quotes.txt'

How can I fix it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Besides using `raw string` - `r"C:\blop\movie_quotes.txt"`, you should use [with open](http://stackoverflow.com/questions/9282967/how-to-open-a-file-using-the-open-with-statement) instead of just `open` – Vaulstein Jul 12 '15 at 16:17

2 Answers2

6

Assuming the file "C:\blop\movie_quotes.txt" exists, Python is converting \b to \x08 before passing it onto open() causing your issue. You should prepend your string with r so that it becomes a raw string, and \b does not get converted to anything (other than \\b , for escaping the \).

Another issue in your code is that you are doing - contents_of_file = quotes.read. This will just put the reference to the read() function in contents_of_file name. I think you want to read the contents of the file, so you should call the read function as - contents_of_file = quotes.read().

Example:

def read_text():
    quotes = open(r"C:\blop\movie_quotes.txt")
    contents_of_file = quotes.read()
    print(contents_of_file)
    quotes.close()
read_text()

You can also, use the with statement here as:

def read_text():
    with open(r"C:\blop\movie_quotes.txt") as quotes:
        contents_of_file = quotes.read()
        print(contents_of_file)
read_text()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
-1

'\b' is a special character in Python. The same as '\n' is a special character meaning the newline character, and '\t' is the tab character, and '\r' is the carriage return character.

'\\\\' is a special character meaning the backslash character. So each time you need a backslash, you need to escape it, and put two backslashes in order to print one.

open("C:\blop\movie_quotes.txt") should be open("C:\\\\blop\\\\movie_quotes.txt")

You have other errors in your code too. You are missing the parenthesis () after each function call, like read() or close().

rassa45
  • 3,482
  • 1
  • 29
  • 43
Mihai Hangiu
  • 588
  • 4
  • 13
  • Build paths need one backslash and the OP does not have to escape the backslashes in a string. He can do something like `r"C:\blop\movie_quotes.txt"`. The `r` reads the backslashes as non-esscape characters. He only needs to escape the backslashes if he is doing something like `\n` in his string – rassa45 Jul 12 '15 at 16:45