Reading lines from a file
Question: I am writing a program to read lines of text from 5 files and compile the text
from these 5 files into respective lists.

However I am having a great deal of trouble getting the program to actually
read the text to a list, here is my code so far:

    
    
    from random import random
    
    from dice import choose
    
    b = open ('E:\Videos, TV etc\Python\ca2\beginning.txt', 'r'). readlines ()
    stripped_b = [item.strip() for item in b]
    
    a = open ('E:\Videos, TV etc\Python\ca2\adjective.txt', 'r'). readlines ()
    stripped_a = [item.strip() for item in a]
    
    i = open ('E:\Videos, TV etc\Python\ca2\inflate.txt', 'r'). readlines ()
    stripped_i = [item.strip() for item in i]
    
    n = open ('E:\Videos, TV etc\Python\ca2\noun.txt', 'r'). readlines ()
    stripped_n = [item.strip() for item in n]
    
    phrase = []
    
    turn = 0
    
    def business_phrase(x):
    
        x = raw_input("\n\nInsert a number of business phrases to generate: ")
        while turn <= x:
            turn += 1
            for item in stripped_b:
                random_word = choose(item)
                phrase.append(random_word)
            for item in stripped_a:
                random_word = choose(item)
                phrase.append(random_word)
            for item in stripped_i:
                random_word = choose(item)
                phrase.append(random_word)
            for item in stripped_n:
                random_word = choose(item)
                phrase.append(random_word)
        print random_list
    

business_phrase(x)

where beginning, adjective, inflate and noun are the text files and dice is a
python file containing the function for choose.

I run this program to try and generate a phrase and I get the following error
message:

    
    
    IOError: [Errno 22] invalid mode ('r') or filename 'E:\\Videos, Tv etc\\Python\\ca2\\x08eginning.txt'
    

I have no idea why it won't read the text files as they are in the same
directory as stated (in fact in the same directory as the program containing
the function).

Does anyone have any ideas I am completely stumped.


Answer: when handling Windows pathnames, always use raw string literals:

    
    
    r'E:\Videos, TV etc\Python\ca2\beginning.txt'
    

because otherwise the backslashes may be interpreted as starting an escape
sequence.

Also, watch out with backslashes at the end of a string: `r'C:\'` is not what
you think it is.

