简体   繁体   中英

Reading lines from a file

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.

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.

'\\' is used for escapes in Python strings. Here's a list of what you can do with them . You want to escape the backslashes to actually have them read as backslahes, which means using two of them. Do this:

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

Raw strings like larsmans suggested will also work!

No, you probably don't have a filename with a ^H in it. Escape your backslashes.

'...\\...'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM